[英]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.