我是 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
with map
:
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
你选len(df)
随机的密钥数量country
键列表,然后使用country
字典作为映射器来查找先前选择的键的对应国家/地区。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)