pandas new column等于另一个有条件的列

时间:2016-10-23 14:07:15

标签: python database pandas numpy dataframe

获得了一个名为data的pd数据库:

                 transaction_id  house_id    date_sale  sale_price boolean_2015
0                     1         1  31 Mar 2016    £880,000         True
3                     4         2  31 Mar 2016    £450,000         True
4                     5         3  31 Mar 2016    £680,000         True
6                     7         4  31 Mar 2016  £1,850,000         True
7                     8         5  31 Mar 2016    £420,000         True

另一个叫房子:

    id                                                  address  postcode       postcode first
0          1  Flat 78, Andrewes House, Barbican, London, Gre...  EC2Y 8AY       EC2Y  
1          2  Flat 35, John Trundle Court, Barbican, London,...  EC2Y 8DJ       EC2Y

问题是我如何在名为'postcode_first'的数据中添加一列,我在其中查找数据['house_id']并将邮政编码的第一部分添加到数据['postcode_first']中的每一行?
我得到的最接近的是

data['postcode'] = np.where(houses['id'] == data['house_id'])

但这根本没有意义 任何帮助人? 编辑 也试过了 data['postcode'] = houses.loc[houses['id'] == data['house_id']]['postcode_first']

但是这返回了

    Traceback (most recent call last):
  File "/Users/saminahbab/Documents/House_Prices/final project/sql_functions.py", line 30, in <module>
    data['postcode'] = houses.loc[houses['id'] == data['house_id']]['postcode_first']
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pandas/core/ops.py", line 735, in wrapper
    raise ValueError('Series lengths must match to compare')
ValueError: Series lengths must match to compare

这不重要,因为我试图基本上说data['postcode'] equals houses['postcode_first'] WHERE houses['id'] equals data['house_id']

1 个答案:

答案 0 :(得分:1)

您可以使用map()方法:

In [108]: df['postcode'] = df.house_id.map(h.set_index('id')['postcode first'])

In [109]: df
Out[109]:
   transaction_id  house_id    date_sale  sale_price boolean_2015 postcode
0               1         1  31 Mar 2016    £880,000         True     EC2Y
3               4         2  31 Mar 2016    £450,000         True     EC2Y
4               5         3  31 Mar 2016    £680,000         True      NaN
6               7         4  31 Mar 2016  £1,850,000         True      NaN
7               8         5  31 Mar 2016    £420,000         True      NaN

数据:

In [110]: h
Out[110]:
   id                                         address  postcode postcode first
0   1  Flat 78, Andrewes House, Barbican, London, Gre  EC2Y 8AY           EC2Y
1   2   Flat 35, John Trundle Court, Barbican, London  EC2Y 8DJ           EC2Y

In [113]: df
Out[113]:
   transaction_id  house_id    date_sale  sale_price boolean_2015
0               1         1  31 Mar 2016    £880,000         True
3               4         2  31 Mar 2016    £450,000         True
4               5         3  31 Mar 2016    £680,000         True
6               7         4  31 Mar 2016  £1,850,000         True
7               8         5  31 Mar 2016    £420,000         True