【问题标题】:pandas Series str replace not working when chained togetherpandas Series str replace 链接在一起时不起作用
【发布时间】:2016-08-20 11:42:40
【问题描述】:

我发现使用链式字符串操作对 Series 进行一些棘手的处理。

我最终发现每个字符串操作都以'.str'为前缀。如果可以像应用程序一样执行链接操作,那就太好了。

这里是代码

# Create dataframe
d = dict(a = ['ab\ncdef'], b = ['bbccdd'])
p = pd.DataFrame.from_dict(d)
print(p)

x1 = p.a.str.replace('c','=').replace('\n','-')[0]
x2 = p.a[0].replace('c','=').replace('\n','-')
x3 = p.apply(lambda r : r.a.replace('c','=').replace('\n','-'),axis=1)[0]
x4 = p.a.str.replace('c','=').str.replace('\n','-')[0]
x1,x2,x3,x4

这是输出。可以看到 x1 不工作,但 x4 工作

      a       b
0  ab\ncdef  bbccdd

('ab\n=def', 'ab-=def', 'ab-=def', 'ab-=def')

由于 x3,x4 是解决方案...我发布此内容主要是为了分享并询问是否应将链式字符串操作应用于单个系列?只是好奇其他人是否遇到了这个问题。

【问题讨论】:

    标签: string pandas replace


    【解决方案1】:

    这样做:

    In [89]: p.a
    Out[89]:
    0    ab\ncdef
    Name: a, dtype: object
    
    In [90]: p.a.str.replace('c','=').str.replace('\n','-')
    Out[90]:
    0    ab-=def
    Name: a, dtype: object
    

    PS注意 .str

    In [91]: p.a.str.replace('c','=').replace('\n','-')
    Out[91]:
    0    ab\n=def
    Name: a, dtype: object
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-03
      • 2012-05-15
      • 1970-01-01
      • 2012-11-17
      相关资源
      最近更新 更多