根据另一个中的值将值添加到pandas数据帧的一列中

时间:2014-03-05 10:32:29

标签: python numpy pandas

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

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

表格如下所示:

Original Data Frame
Original Table:
  col1 col2  col3
0    a    c     1
1    a    d     2
2    b    c     3
3    b    d     4

Reference Table:
  col1 col2  col3
0    x    c    10
1    x    d    20

现在我想从原始表(a)的第三列(col3)中减去两个表的第二列匹配的行中引用表(c)中的值。因此,表2的第一行应该将值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'中的结果不应该是列表。使用numpy的解决方案也很受欢迎。

1 个答案:

答案 0 :(得分:1)

我不太明白你对你要做什么的描述,但是你所显示的输出可以通过首先合并两个数据帧然后进行一些简单的操作来生成;

>>> df = a.merge(b.filter(['col2', 'col3']), how='left',
                 left_on='col2', right_on='col2', suffixes=('', '_'))
>>> df
  col1 col2  col3  col3_
0    a    c     1     10
1    b    c     3     10
2    a    d     2     20
3    b    d     4     20

[4 rows x 4 columns]
>>> df.col3_.fillna(0, inplace=True) # in case there are no matches
>>> df.col3 += df.col3_
>>> df
  col1 col2  col3  col3_
0    a    c    11     10
1    b    c    13     10
2    a    d    22     20
3    b    d    24     20

[4 rows x 4 columns]
>>> df.drop('col3_', axis=1, inplace=True)
>>> df
  col1 col2  col3
0    a    c    11
1    b    c    13
2    a    d    22
3    b    d    24

[4 rows x 3 columns]

如果col2中的b中的值不是唯一的,那么您可能还需要以下内容:

>>> b.groupby('col2', as_index=False)['col3'].aggregate(sum)
相关问题