1 回答
TA贡献1793条经验 获得超6个赞
我认为您要做的是整理每次点击的国家/地区信息数据:
# I take the example with two lists for link-level data related to countries, but
# it extends to more :
import pandas as pd
countries_data1 = [
{'country': 'US', 'clicks': 150}, {'country': 'UK', 'clicks': 20},
{'country': 'AU', 'clicks': 45}, {'country': 'ZS', 'clicks': 31}
]
countries_data2 = [
{'country': 'US', 'clicks': 150}, {'country': 'UK', 'clicks': 20},
{'country': 'AU', 'clicks': 45}, {'country': 'ZS', 'clicks': 31}
]
# transform to dataframe, add variable link, and concat
countries_data1 = pd.DataFrame(countries_data1).assign(link="bit.ly/aaaa")
countries_data2 = pd.DataFrame(countries_data2).assign(link="bit.ly/bbbb")
df = pd.concat([countries_data1, countries_data2]) # you will concat the list of all
# your dataframes with link information regarding countries, here I only have 2 in
# this example
# then go in wide format with pivot_table
df = df.pivot_table(index="link", values="clicks", columns="country")
你得到这个表:
country AU UK US ZS
link
bit.ly/aaaa 45 20 150 31
bit.ly/bbbb 45 20 150 31
# assume your first table (simplified) is :
table = pd.DataFrame({"link": ["bit.ly/aaaa", "bit.ly/bbbb"],
"link_clicks": [150,20]})
# set the index for link
table = table.set_index("link")
# then do an outer join on link
merge_df = pd.concat([table, df], join="outer", axis=1)
merge_df.head()
您得到的结果:
link_clicks AU UK US ZS
link
bit.ly/aaaa 150 45 20 150 31
bit.ly/bbbb 20 45 20 150 31
添加回答
举报