更改字符串的缩写

时间:2017-02-06 23:19:45

标签: python

尝试更改缩写地址以完整描述结束,但回溯没有任何意义。请告诉我这里我做错了什么。

import pandas as pd

edit = pd.read_csv('mycsvfile')

edit['Home'] = edit['Home'].apply(lambda s: s.replace('Ct', 'Court'))
edit['Home'] = edit['Home'].apply(lambda s: s.replace('Rd', 'Road'))
edit['Home'] = edit['Home'].apply(lambda s: s.replace('Ln', 'Lane'))

edit.to_csv('newcsvfile',index = False)
Traceback (most recent call last):
File "C:\Users\.py", line 20, in <module>
edit['Home'] = edit['Home'].apply(lambda s: s.replace('Ct', 'Court'))
File "C:\********.py", line 2294, in apply
mapped = lib.map_infer(values, f, convert=convert_dtype)
File "pandas\src\inference.pyx", line 1207, in pandas.lib.map_infer (pandas\lib.c:66124)
File "C:******.py", , in <lambda>
edit['Home'] = edit[Home'].apply(lambda s: s.replace('Ct', 'Court'))
AttributeError: 'float' object has no attribute 'replace'

以下是Home列中的一些值:

1458 Clearlight Rd
7458 Grove Ln
8574 Grove Ct
2222 Grove Ln
1258 Grove Ct
1478 Grove Ln

1 个答案:

答案 0 :(得分:5)

缺少Home列中的某些值。熊猫将缺失值视为numpy nan,它们属于float类型。

您有几个选择:

  1. 使用np.nan之外的其他内容填充您的缺失值:http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.DataFrame.fillna.html (在阅读csv时填写缺失值:http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html

  2. 过滤非空值,然后应用您的函数:

  3. edit[edit['Home'].notnull()]['Home'].apply(lambda s: s.replace('Ct', 'Court')