【发布时间】:2019-07-15 10:48:17
【问题描述】:
我想让所有字符串都小写并删除字符串开头和结尾的空格。
df = pandas.DataFrame(data=[1,2,3,'A'],columns=['A'])
df['A'] = numpy.where(
df['A'].apply(lambda x: isinstance(x, str)),
df['A'].str.lower().str.strip(),
df['A'],
)
问题是如果没有行是字符串,上面的代码就会失败。
df = pandas.DataFrame(data=[1,2,3],columns=['A'])
AttributeError: Can only use .str accessor with string values, which use np.object_ dtype in pandas
有没有比这个更好的方法
for index in df['A'].index:
if isinstance(df['A'].iloc[index], str):
df['A'].iloc[index] = df['A'].iloc[index].str.lower().str.strip()
【问题讨论】:
-
我认为这是一个丑陋的错误 :(
-
使用
df['A']=df['A'].apply(lambda x: x.lower().strip() if isinstance(x, str) else x)
标签: python string pandas numpy dataframe