修改pandas dataframe列中的字符串

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了修改pandas dataframe列中的字符串相关的知识,希望对你有一定的参考价值。

我想将所有字符串设置为小写,并删除字符串开头和结尾的空格。

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) 

以上是关于修改pandas dataframe列中的字符串的主要内容,如果未能解决你的问题,请参考以下文章