[英]add values to data frame for only some specific elements - python
With these two data frames有了这两个数据框
df1 = pd.DataFrame({'c1':['a','b','c','d'],'c2':[10,20,10,22]})
df2 = pd.DataFrame({'c3':['e','f','a','g','b','c','r','j','d'],'c4':[1,2,3,4,5,6,7,8,9]})
I'm trying to add the values of c4
to df1
for only the elements in c3
that are also present in c1
:我正在尝试将
c4
的值添加到df1
仅用于c3
中也存在于c1
的元素:
>>> df1
c1 c2 c4
a 10 3
b 20 5
c 10 6
d 22 9
Is there a simple way of doing this in pandas?在熊猫中是否有一种简单的方法可以做到这一点?
UPDATE:更新:
If如果
df2 = pd.DataFrame({'c3':['e','f','a','g','b','c','r','j','d'],'c4':[1,2,3,4,5,6,7,8,9]},'c5':[10,20,30,40,50,60,70,80,90])
how can I achieve this result?我怎样才能达到这个结果?
>>> df1
c1 c2 c4 c5
a 10 3 30
b 20 5 50
c 10 6 60
d 22 9 90
Doing:正在做:
>>> df1['c1'].map(df2.set_index('c3')['c4','c5'])
gives me a KeyError
给我一个
KeyError
You can call map
on df2['c4']
after setting the index on df2['c3']
, this will perform a lookup:在
df2['c3']
上设置索引后,您可以在df2['c4']
上调用map
,这将执行查找:
In [239]:
df1 = pd.DataFrame({'c1':['a','b','c','d'],'c2':[10,20,10,22]})
df2 = pd.DataFrame({'c3':['e','f','a','g','b','c','r','j','d'],'c4':[1,2,3,4,5,6,7,8,9]})
df1['c4'] = df1['c1'].map(df2.set_index('c3')['c4'])
df1
Out[239]:
c1 c2 c4
0 a 10 3
1 b 20 5
2 c 10 6
3 d 22 9
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.