繁体   English   中英

pandas 字符串替换 TypeError - 使用 pandas df 列替换单词

[英]pandas string replace TypeError - replace words using pandas df column

我正在使用 Python 3.7 并且有一个包含一列地址的大型数据框,如下所示:

c = ['420 rodeo drive', '22 alaska avenue', '919 franklin boulevard', '39 emblem alley', '67 fair way']
df1 = pd.DataFrame(c, columns = ["address"])

还有地址缩写的dataframe及其usps版本。 一个例子:

x = ['avenue', 'drive', 'boulevard', 'alley', 'way']
y = ['aly', 'dr', 'blvd', 'ave', 'way']
df2 = pd.DataFrame(list(zip(x,y)), columns = ['common_abbrev', 'usps_abbrev'], dtype = "str")

我想做的是如下:

  1. df1['address']中搜索df2['common_abbrev']中出现的单词并替换为df2['usps_abbrev']
  2. 返回转换后的df1

为此,我尝试了几种方法,似乎是df.str.replace()的规范策略,如下所示:

df1["address"] = df1["address"].str.replace(df2["common_abbrev"], df2["usps_abbrev"])

但是,我收到以下错误:

`TypeError: repl must be a string or callable`.

我的问题是:

  1. 既然我已经给出了df2dtype ,为什么我会收到错误消息?

  2. 我怎样才能产生我想要的结果:

     address 0 420 rodeo dr 1 22 alaska ave 2 919 franklin blvd 3 39 emblem aly 4 67 fair way

谢谢你的帮助。

首先使用zip创建一个dict 然后使用Series.replace

In [703]: x = ['avenue', 'drive', 'boulevard', 'alley', 'way']
     ...: y = ['aly', 'dr', 'blvd', 'ave', 'way']

In [686]: d = dict(zip(x, y))

In [691]: df1.address = df1.address.replace(d, regex=True)

In [692]: df1
Out[692]: 
             address
0       420 rodeo dr
1      22 alaska aly
2  919 franklin blvd
3      39 emblem ave
4        67 fair way

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM