修改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列中的字符串的主要内容,如果未能解决你的问题,请参考以下文章

pandas移除dataframe字符串数据列中的后N个字符(remove the last n characters from values from column of dataframe)

pandas使用replace函数将dataframe指定数据列中的特定字符串进行自定义替换(replace substring in dataframe column values)

pandas移除dataframe字符串数据列中的前N个字符(remove the first n characters from values from column of dataframe)

从pandas DataFrame中另一列中的位置给定的字符串列中提取字符[重复]

从 pandas DataFrame 中的列中提取 JSON 数据

获取 Pandas DataFrame 列中字符串列表中的所有行 - 此模式具有匹配组