【问题标题】:Replace parts of a single column替换单个列的部分
【发布时间】:2017-06-23 18:57:56
【问题描述】:

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

1234 Edison Ln -----------> 1234 Edison Lane

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

【问题讨论】:

标签: python pandas


【解决方案1】:

你可以使用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

【讨论】:

  • 谢谢,但是值是这样的 1234 Edison Ln, 4785 Stack Overflow Dr。这就是我使用 str 的原因。
  • 我试过 pd.DataFrame.replace({mycsv['Address']:......它仍然抛出同样的错误。
  • 更新了答案
猜你喜欢
  • 1970-01-01
  • 2020-10-02
  • 1970-01-01
  • 2013-08-23
  • 1970-01-01
  • 2016-06-10
  • 2016-08-14
  • 1970-01-01
  • 2015-05-12
相关资源
最近更新 更多