【发布时间】:2017-10-01 15:27:15
【问题描述】:
我正在尝试匹配从bad_boy 到good_boy 的部分字符串,并在原始df (bad_boy) 中创建一个名为Right Address 的列,但很难实现这一目标。我查看了以下链接:
Replace whole string if it contains substring in pandas
Return DataFrame item using partial string match on rows pandas python
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]'
正在请求结果:
print (df['Right Address'].head(3))
0 1234 Stack Overflow Way
1 7458 Python Avenue
2 8745 Pandas Lane
【问题讨论】:
-
您的数字列 1234、7458 和 8745 在您的两个数据框中都匹配。您可以加入并保留 df2 名称吗?这会给你想要的结果。还是你需要通过字符串匹配来做到这一点?
-
那会很好,但是有什么想法吗?