在使用 Python 时,你可能遇到的一个错误是:
AttributeError: Can only use .str accessor with string values!
这个错误通常发生在你试图替换 pandas DataFrame 的字符串列中的一个模式,但是你所处理的列实际上并不是一个字符串。
下面的例子展示了如何在实践中解决这个错误。
如何重现这个错误
假设我们有下面这个pandas DataFrame:
import pandas as pd
#create DataFrame
df = pd.DataFrame({'team': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],
'points': [6.5, 7.8, 8.0, 9.0, 7.5, 3.4, 6.6, 6.8],
'assists': [5, 7, 7, 9, 12, 9, 9, 4],
'rebounds': [11, 8, 10, 6, 6, 5, 9, 12]})
#view DataFrame
df
team points assists rebounds
0 A 6.5 5 11
1 A 7.8 7 8
2 A 8.0 7 10
3 A 9.0 9 6
4 B 7.5 12 6
5 B 3.4 9 5
6 B 6.6 9 9
7 B 6.8 4 12
现在假设我们试图将 "积分 "列中的每个小数点都替换成空白:
#attempt to replace decimal in "points" column with a blank
df['points'] = df['points'].str.replace('.', '')
AttributeError: Can only use .str accessor with string values!
我们会收到一个错误,因为 "积分 "列不是一个字符串列。
如何修复这个错误
绕过这个错误的最简单方法是在试图替换 "积分 "列中的任何数值之前使用.astype(str)函数:
#replace decimal in "points" column with a blank
df['points'] = df['points'].astype(str).str.replace('.', '')
#view updated DataFrame
df
team points assists rebounds
0 A 65 5 11
1 A 78 7 8
2 A 80 7 10
3 A 90 9 6
4 B 75 12 6
5 B 34 9 5
6 B 66 9 9
7 B 68 4 12
注意,"积分 "列中的每个小数点都已被替换,而且我们没有收到任何错误,因为我们在试图替换 "积分 "列中的任何数值之前使用了.astype(str)函数。
注意:你可以在这里找到replace()函数的完整文档。
其他资源
下面的教程解释了如何修复Python中的其他常见错误:
如何修复Pandas中的KeyError
如何修复ValueError: 无法将浮点数NaN转换为整数
如何修复ValueError:操作数不能与形状一起广播