我会尽量简化。我有一个按州列出的数据框。有些州是缩写,有些不是。我想用缩写代替全州名(例如:新泽西州到新泽西州)。在
我发现了一个很酷的模块“US”foundhere,它列出了字典中所有的状态及其缩写。我想做的是用缩写代替全名。在
代码:
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_键代替。在
如果您能够解释如何将此应用于Dataframe的“C”列,则需要额外说明
以下是完整的解决方案:
首先,我将定义一个函数,它将替换字符串中状态的全名(如果存在的话),或者返回原始字符串。在
然后可以将此函数应用于dataframe的整个列
^{pr2}$相关问题 更多 >
编程相关推荐