python - 更换单列的部件

标签 python pandas

我需要将部分缩写地址替换为新 csv 中的完整地址,但仍然遇到错误。我该如何解决这个问题?

1234 爱迪生巷 -----------> 1234 爱迪生巷

4589 Stack Overflow Dr -----------> 4589 Stack Overflow Drive

import pandas as pd

mycsv = pd.read_csv('addressescsv')
mycsv['Address'] = str.replace({mycsv['Address']: {'Ln': 'Lane','Dr': 'Drive'}})

mycsv.to_csv('newAddressescsv', index=False)

Traceback:

Traceback (most recent call last):
File "C:\movingalong.py", line 8, in <module>
File "C:\Users\Programs\Python\Python36-32\lib\site-
packages\pandas\core\generic.py", line 831, in __hash__
' hashed'.format(self.__class__.__name__))
TypeError: 'Series' objects are mutable, thus they cannot be hashed

最佳答案

您可以使用DataFrame.replace

df = pd.DataFrame({'Address':['Ln', 'Dr', 'High']})
print df.replace({'Address' :{'Ln': 'Lane','Dr': 'Drive'}})

输出

       Address
0   Lane
1  Drive
2   High

由于您正在寻找部分匹配,您可能想尝试一下

import re
import pandas as pd 

df = pd.DataFrame({'Address':['City Ln', 'New Dr', 'Ln']})
rep = {'Ln': 'Lane','Dr': 'Drive'}
regex = re.compile(r"\b((%s)\S*)\b" %"|".join(rep.keys()), re.I)

def dictionary_lookup(match):
    return rep[match.group(2)]

def ReplaceStr(value):
    NewValue = regex.sub(dictionary_lookup, value)
    return NewValue


df["New Address"] = df["Address"].map(lambda x:ReplaceStr(x))
print df

输出

   Address New Address
0  City Ln   City Lane
1   New Dr   New Drive
2       Ln        Lane

灵感来自https://stackoverflow.com/a/32191354/6626530

关于python - 更换单列的部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42074484/

相关文章:

python - Pandas 离开加入到位

python - 如何在django的sqlite3数据库中使用全文搜索?

python 无法使用 virtualenv

python - 将某一列中的行值与其他列中的值进行比较

python - 在缺少第一个和最后一个值的情况下用 Pandas 插入两个方向?

python: pandas .describe - 如何将结果放入变量中?

Python:将请求置于休息 api 发送 Bad request 400 错误

python - UnicodeEncodeError : 'ascii' codec can't encode character u'\u201c' in position 34: ordinal not in range(128)

python - 计算文件中所有可能的长度为 n 的子字符串? (不包括空格)

python - Pandas : Is there a way to count the number of occurrences of values in a given column which contains dictionaries values in the cells?