【问题标题】:Extract last specific word/value from one column and move it to the next row从一列中提取最后一个特定的单词/值并将其移至下一行
【发布时间】:2023-01-25 17:04:56
【问题描述】:

我有一个像下面这样的数据框

|Animals        | Type         | Year |
|Penguin AVES   | Omnivore     | 2015 |
|Caiman REP     | Carnivore    | 2018 |
|Komodo.Rep     | Carnivore    | 2019 |
|Blue Jay.aves  | Omnivore     | 2015 |
|Iguana+rep     | Carnivore    | 2020 |

我想从“动物”列的值中提取最后的特定单词(例如 AVES 和 REP),并将其移动到下一行,同时保留整行的值。除了 AVES 和 REP 之外,还有几个特定的​​词。它不是很干净(如特定单词前的空格、点和“+”运算符所示)。预期的新 DataFrame 如下所示

| Animals        | Type         | Year |
| Penguin AVES   | Omnivore     | 2015 |
| AVES           | Omnivore     | 2015 |
| Caiman REP     | Carnivore    | 2018 |
| REP            | Carnivore    | 2018 |
| Komodo.Rep     | Carnivore    | 2019 |
| Rep            | Carnivore    | 2019 |
| Blue Jay.aves  | Omnivore     | 2015 |
| aves           | Omnivore     | 2015 |
| Iguana+rep     | Carnivore    | 2020 |
| rep            | Carnivore    | 2020 |

我正在考虑使用负索引来拆分字符串,但我对这个特定问题的 lambda 函数感到困惑。知道我应该如何解决这个问题吗?提前致谢。

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    您可以使用str.extract获取最后一个词((w+)$正则表达式,但如果需要,您也可以使用特定列表(?i)(aves|rep)$)和assign它来替换列,然后concat更新的DataFrame到原始的,和 sort_index 用稳定的方法交错行:

    out = (pd.concat([df, df.assign(Animals=df['Animals'].str.extract(r'(w+)$'))])
             .sort_index(kind='stable', ignore_index=True)
          )
    

    输出:

             Animals       Type  Year
    0   Penguin AVES   Omnivore  2015
    1           AVES   Omnivore  2015
    2     Caiman REP  Carnivore  2018
    3            REP  Carnivore  2018
    4     Komodo.Rep  Carnivore  2019
    5            Rep  Carnivore  2019
    6  Blue Jay.aves   Omnivore  2015
    7           aves   Omnivore  2015
    8     Iguana+rep  Carnivore  2020
    9            rep  Carnivore  2020
    

    【讨论】:

    • 如果有下划线作为分隔符,我会使用 r'[W_](w+)$' 代替
    • 在这种情况下我会使用([a-zA-Z]+)$,无论如何这部分可以由 OP 轻松调整;)
    猜你喜欢
    • 2023-01-26
    • 2023-01-22
    • 1970-01-01
    • 2012-02-05
    • 1970-01-01
    • 1970-01-01
    • 2021-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多