[英]How to fill pandas dataframe columns with random dictionary values
我是 Pandas 的新手,我想玩随机文本数据。 我正在尝试向 DataFrame df 添加 2 个新列,每个列都由从字典中随机选择的键 (newcol1) + 值 (newcol2) 填充。
countries = {'Africa':'Ghana','Europe':'France','Europe':'Greece','Asia':'Vietnam','Europe':'Lithuania'}
我的 df 已经有 2 列,我想要这样的东西:
Year Approved Continent Country
0 2016 Yes Africa Ghana
1 2016 Yes Europe Lithuania
2 2017 No Europe Greece
我当然可以使用 for 或 while 循环来填充 df['Continent'] 和 df['Country'] 但我觉得 .apply() 和 np.random.choice 可能会为此提供一个更简单、更有趣的解决方案。
是的,你说得对。 您可以将np.random.choice
与map
np.random.choice
使用:
df
Year Approved
0 2016 Yes
1 2016 Yes
2 2017 No
df['Continent'] = np.random.choice(list(countries), len(df))
df['Country'] = df['Continent'].map(countries)
df
Year Approved Continent Country
0 2016 Yes Africa Ghana
1 2016 Yes Asia Vietnam
2 2017 No Europe Lithuania
您从country
密钥列表中随机选择len(df)
个密钥,然后使用country
词典作为映射器来查找先前选择的密钥的国家/地区等价物。
您也可以尝试使用DataFrame.sample()
:
df.join(
pd.DataFrame(list(countries.items()), columns=["continent", "country"])
.sample(len(df), replace=True)
.reset_index(drop=True)
)
如果您的大陆国家地图已经是数据框,则可以更快。
如果您使用的是 Python 3.6,另一种方法是使用random.choices()
:
df.join(
pd.DataFrame(choices([*countries.items()], k=len(df)), columns=["continent", "country"])
)
random.choices()
是类似于numpy.random.choice()
不同之处在于可以通过键-值元组对,而列表numpy.random.choice()
只接受1-d阵列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.