我想从像这样的数据框中替换列中的一些字符串
df["column"]
------------------
1. Ne Road
2. Rosemarys street se
3. Plunkett pkwy
4. like that so on.....
像这些有成千上万的价值观
在这里,我想将Ne替换为NE,将SE替换为SE,pkwy替换为Parkway
所以这是我的代码:
def replace_all(text, dic):
for i, j in dic.items():
text = text.replace(i, j)
return text
my_text = df.iloc[:,2] -----### '2' is the Column number here in my Dataframe ###
reps = {
'se' : 'SE'
'Ne' : 'NE'
'pkwy' :'"Parkway'
}
df["column"] = replace_all(my_text,reps)
我想知道我哪里出错了,请帮我解决这个问题。
提前致谢!!
答案 0 :(得分:0)
这是一种使用apply
与lambda
<强>演示:强>
import pandas as pd
def replaceString(val):
reps = {
'se' : 'SE',
'Ne' : 'NE',
'pkwy' :'"Parkway',
'sw': "SW",
'rd':"Road"
}
for key, v in reps.items():
if key in val:
val = val.replace(key, v)
return val
df = pd.DataFrame({"column": ['Ne Road', 'Rosemarys street se', "Plunkett pkwy", "sw Trampoline rd"]})
print(df["column"].apply(replaceString))
<强>输出:强>
0 NE Road
1 RoSEmarys street SE
2 Plunkett "Parkway
3 SW Trampoline Road
Name: column, dtype: object
答案 1 :(得分:0)
您可以将pd.Series.replace
与参数regex=True
一起使用:
df = pd.DataFrame({'column': ['Ne Road', 'Rosemarys street se',
'Plunkett pkwy', 'like that so on']})
reps = {'se' : 'SE', 'Ne' : 'NE', 'pkwy': 'Parkway'}
df['column'] = df['column'].replace(reps, regex=True)
print(df)
column
0 NE Road
1 RoSEmarys street SE
2 Plunkett Parkway
3 like that so on