python - 如果数据框中的另一列使用 pandas 匹配某个值,则从数据框中的列中减去值

标签 python pandas data-science

假设我有两个矩阵原始和引用

import pandas as pa
print "Original Data Frame"
# Create a dataframe
oldcols = {'col1':['a','a','b','b'], 'col2':['c','d','c','d'], 'col3':[1,2,3,4]}
a = pa.DataFrame(oldcols)
print "Original Table:"
print a

print "Reference Table:"
b = pa.DataFrame({'col1':['x','x'], 'col2':['c','d'], 'col3':[10,20]})
print b

现在我想从原始表 (a) 的第三列 (col3) 中减去两个表的第二列匹配的行中引用表 (c) 中的值。因此表二的第一行应该将值 10 添加到第三列,因为表 b 中列为 col2 的行在 col3 中的值为 10。合理?下面是一些执行此操作的代码:

col3 = []
for ix, row in a.iterrows():
    col3 += [row[2] + b[b['col2'] == row[1]]['col3']]

a['col3'] = col3
print "Output Table:"
print a

并想让它看起来像这样:

Output Table:
  col1 col2  col3
0    a    c   11
1    a    d   22
2    b    c   13
3    b    d   24

问题是 col3 在数组中采用 Name: 和 dtype

>>print col3
[0    11
Name: col3, dtype: int64, 1    22
Name: col3, dtype: int64, 0    13
Name: col3, dtype: int64, 1    24
Name: col3, dtype: int64]

你能帮忙吗?

最佳答案

这应该有效:

a['col3'] + a['col2'].map(b.set_index('col2')['col3'])
Out[94]: 
0    11
1    22
2    13
3    24
dtype: int64

或者这个:

a.merge(b, on='col2', how='left')[['col3_x', 'col3_y']].sum(axis=1)
Out[110]: 
0    11
1    22
2    13
3    24
dtype: int64

您可以根据要求通过以下方式将其存储在原始版本中:

a['col3'] = a.merge(b, on='col2', how='left')[['col3_x', 'col3_y']].sum(axis=1)

关于python - 如果数据框中的另一列使用 pandas 匹配某个值,则从数据框中的列中减去值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38459794/

相关文章:

python - 在 Linux 上安装 Azure Python api : importError: No module named storage. blob

loops - 如何在pandas数据框中的特定列中搜索字符串值,如果存在,则给出数据框中存在的该行的输出?

python - 总结 DataFrame 中的行,同时保持类似的 DataFrame 结构

python - 将每日时间序列透视为 Pandas 中的周行

apache-spark - 使用 Spark ML 进行文本分类

python - 不使用类时使用映射或类似方法更新字典

Python属性错误: module 'string' has no attribute 'maketrans'

python - 从子包访问共享模块

c - 如何从 Octave 或 Matlab 中的文件加载 C 结构体

python - 评分系统 - 输入特征