【问题标题】:modify strings in pandas dataframe column修改 pandas 数据框列中的字符串
【发布时间】: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


【解决方案1】:

假设您想保持非字符串不变,您可以使用:

df['A']=df['A'].apply(lambda x: x.lower().strip() if isinstance(x, str) else x) 

【讨论】:

    猜你喜欢
    • 2019-04-19
    • 2016-05-11
    • 1970-01-01
    • 2018-04-26
    • 1970-01-01
    • 2019-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多