【问题标题】:substract values from column in dataframe if another column in dataframe matches some value using pandas如果数据框中的另一列使用熊猫匹配某个值,则从数据框中的列中减去值
【发布时间】:2016-07-19 13:18:28
【问题描述】:

说我有两个矩阵原始和参考

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 添加到第三列,因为列是 col2 的表 b 的行是 'c' 在 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]

你能帮忙吗?

【问题讨论】:

    标签: python pandas data-science


    【解决方案1】:

    这应该可行:

    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)
    

    【讨论】:

      猜你喜欢
      • 2019-08-07
      • 1970-01-01
      • 2013-12-04
      • 1970-01-01
      • 2017-02-20
      • 1970-01-01
      • 2020-07-06
      • 2019-05-20
      • 2019-01-20
      相关资源
      最近更新 更多