【问题标题】:Use a split function in every row of one column of a data frame在数据框的一列的每一行中使用拆分函数
【发布时间】:2023-03-26 10:40:01
【问题描述】:

我有一个相当大的 pandas 数据框(超过 100 万行),其中的列包含字符串或数字。现在我想在“应用”表达式之前将字符串拆分为一列。

一个例子来解释我的意思:

我有什么:

a    b    description
2    4    method A is applied
10   5    titration is applied
3    1    computation is applied

我在寻找什么:

 a    b    description
 2    4    method A 
 10   5    titration 
 3    1    computation 

我尝试了以下,

df.description = df.description.str.split('is applied')[0]

但这并没有带来预期的结果。

任何想法如何做到这一点? :-)

【问题讨论】:

    标签: python-3.x pandas dataframe split


    【解决方案1】:

    你很亲密,需要str[0]

    df.description = df.description.str.split(' is applied').str[0]
    

    替代解决方案:

    df.description = df.description.str.extract('(.*)\s+is applied')
    

    print (df)
        a  b  description
    0   2  4     method A
    1  10  5    titration
    2   3  1  computation
    

    但为了获得更好的性能,请使用list comprehension:

    df.description = [x.split(' is applied')[0] for x in df.description]
    

    【讨论】:

    • 列表理解的解决方案是完美的!非常感谢!
    【解决方案2】:

    你可以使用replace

    df.description = df.description.str.replace(' is applied','')
    df
        a  b  description
    0   2  4     method A
    1  10  5    titration
    2   3  1  computation
    

    【讨论】:

      猜你喜欢
      • 2021-08-18
      • 2017-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-13
      相关资源
      最近更新 更多