![](/img/trans.png)
[英]Pandas: adding a column to a dataframe from dictionary, when keys are the indices of the dataframe
[英]Create pandas dataframe column from another column that has dictionary keys
我有數據框和字典。 這些看起來像
import pandas as pd
df1 = pd.DataFrame({'first':['john','oliver','sarah']})
df1_map = {'john': 'anderson', 'oliver': 'smith', 'sarah' : 'shively'}
print (df1)
print (df1_map)
first
0 john
1 oliver
2 sarah
{'oliver': 'smith', 'sarah': 'shively', 'john': 'anderson'}
df1 ['first']的值表示字典的鍵值。
我想在數據幀中添加第二列df1 ['second'],以便保持dict關系以獲得以下數據幀,
first last
0 john anderson
1 oliver smith
2 sarah shively
現在,我可以像這樣遍歷數據框的值,
df1['last'] = [ df1_map[i] for i in list(df1['first'])]
我想知道熊貓是否支持矢量化的實現/功能,而該實現/功能可以做到這一點而無需遍歷df的行
您可以使用以下命令將字典值直接映射到鍵:
df1['last'] = df1['first'].map(df1_map)
結果是:
Out[6]:
first last
0 john anderson
1 oliver smith
2 sarah shively
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.