gpt4 book ai didi

python - 用字典的值替换字符串

转载 作者:太空宇宙 更新时间:2023-11-04 10:03:04 24 4
gpt4 key购买 nike

我会尽量简化。我有一个 DataFrame,其中包含各州的企业列表。有些州是缩写的,有些则不是。我想用缩写替换完整的州名称(例如:新泽西州到新泽西州)。

我找到了一个很酷的模块“US”found here,它在字典中列出了所有州及其缩写。我想做的是用缩写替换全名。

代码:

import pandas as pd
import numpy as np
import us
dfp = pd.DataFrame({'A' : [np.NaN,np.NaN,3,4,5,5,3,1,5,np.NaN],
'B' : [1,0,3,5,0,0,np.NaN,9,0,0],
'C' : ['Pharmacy of Oklahoma','NY Pharma','NJ Pharmacy','Idaho Rx','CA Herbals','Florida Pharma','AK RX','Ohio Drugs','PA Rx','USA Pharma'],
'D' : [123456,123456,1234567,12345678,12345,12345,12345678,123456789,1234567,np.NaN],
'E' : ['Assign','Unassign','Assign','Ugly','Appreciate','Undo','Assign','Unicycle','Assign','Unicorn',]})
print(dfp)

statez = us.states.mapping('abbr', 'name')
lst_of_abbrv = statez.keys()
lst_of_states = statez.values()

phrase = "Pharmacy of Oklahoma"

for x in phrase.split():
if x in lst_of_states:
x= x.replace(x, 'State')
print(phrase.split())

现在我唯一能做的就是使用一个字符串并将其替换为单词“State”。我如何用字典中的缩写替换名称?我试过并想要像 x= x.replace(x, lst_of_abbrv) 这样的东西但它会出错,因为你显然不能用 dict_keys 替换。

如果您能够解释如何将其应用于 Dataframe 的“C”列,则加分

最佳答案

首先,我将定义一个函数,该函数将替换字符串中状态的完整名称(如果存在)或返回原始字符串。

def replace_states(company):
# find all states that exist in the string
state_found = filter(lambda state: state in company, statez.keys())

# replace each state with its abbreviation
for state in state_found:
company = company.replace(state, statez[state])
# return the modified string (or original if no states were found)
return company

然后您可以将此函数应用于数据框的整个列

dfp['C'] = dfp['C'].map(replace_states)

关于python - 用字典的值替换字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42446792/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com