簡體   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