簡體   English   中英

根據另一個中的值將值添加到pandas數據幀的一列中

[英]Add values to one column of a pandas dataframe based on the values in another

假設我有兩個矩陣,一個原始和一個參考:

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的解決方案也是受歡迎的。

我不太明白你對你要做什么的描述,但是你所顯示的輸出可以通過首先合並兩個數據幀然后一些簡單的操作來生成;

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

如果bcol2中的值不是唯一的,那么您可能還需要以下內容:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM