匹配两个数据帧之间的字符串并创建列

时间:2017-05-03 17:05:57

标签: python pandas

我正在尝试匹配从<tr ng-repeat="x in table"> <td ng-repeat="y in x track by $index" align="center" ng-click="changeProp($index==0 ? 0 :$index--, $index)"> {{ y.display }} </td> </tr> bad_boy的字符串部分,并在原始df(good_boy)中创建一个名为bad_boy的列,但很难获得这完成了。我看了下面的链接:

Replace whole string if it contains substring in pandas

Return DataFrame item using partial string match on rows pandas python

Right Address

我试过了:

import pandas as pd
bad_boy = pd.read_excel('C:/Users/Programming/.xlsx')
df = pd.DataFrame(bad_boy)

print (df['Address'].head(3))

0  1234 Stack Overflow
1  7458 Python
2  8745 Pandas

good_boy = pd.read_excel('C:/Users/Programming/.xlsx')

df2 = pd.DataFrame(good_boy)

print (df2['Address'].head(10))

0 5896 Java Road
1 1234 Stack Overflow Way
2 7459 Ruby Drive
3 4517 Numpy Creek Way
4 1642 Scipy Trail
5 7458 Python Avenue
6 8745 Pandas Lane
7 9658 Excel Road
8 7255 Html Drive
9 7459 Selenium Creek Way

但这会引发错误:

df['Right Address'] = df.loc[df['Address'].str.contains('Address', case = False, na = False, regex = False), df2['Address']]

请求结果:

'None of [0.....all addresses\nName: Address, dtype: object] are in the [columns]'

1 个答案:

答案 0 :(得分:4)

您可以将merge与str.extract结合使用以进行部分匹配

df1 = df1.merge(df2, left_on = df1.Address.str.extract('(\d+)', expand = False), right_on = df2.Address.str.extract('(\d+)', expand = False), how = 'inner').rename(columns = {'Address_y': 'Right_Address'})

你得到了

    Address_x           Right_Address
0   1234 Stack Overflow 1234 Stack Overflow Way
1   7458 Python         7458 Python Avenue
2   8745 Pandas         8745 Pandas Lane