python - 仅针对某些特定元素向数据框添加值 - python

标签 python pandas dataframe

有了这两个数据框

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]})

我尝试将 c4 的值添加到 df1,仅针对 c3 中也存在于 中的元素c1:

>>> df1
  c1  c2  c4
  a   10  3  
  b   20  5
  c   10  6
  d   22  9

在 pandas 中是否有一种简单的方法可以做到这一点?

更新:

如果

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])

我怎样才能达到这个结果?

>>> df1
  c1  c2  c4  c5
  a   10  3   30  
  b   20  5   50
  c   10  6   60
  d   22  9   90

正在做:

>>> df1['c1'].map(df2.set_index('c3')['c4','c5'])

给了我一个KeyError

最佳答案

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

关于python - 仅针对某些特定元素向数据框添加值 - python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31748714/

相关文章:

Python如何使用字符串键索引多维数组,如字典

python - Pandas,如何为所有以数字开头的列名附加前缀?

python - 有没有一种方法可以有效地转换 DataFrame 列中的数据类型?

python - readthedocs突然无法安装scipy

python - 合并字典中的键值对

python-3.x - 为什么我会收到 Pandas 的 HTTP 403 错误?

python - 如何根据一列值和其他条件更改DataFrame列值

python - 如何获取数据框中两个重叠日期之间的范围?

python - 命令完成在 Hg 代码的哪个位置实现?

python - 如何将多个参数传递给 apply 函数