【问题标题】:Create new column based on end of a string with different lengths in pandas根据熊猫中不同长度的字符串的结尾创建新列
【发布时间】:2021-07-31 18:35:42
【问题描述】:

数据框

   description               total      average      number
0 NFL football (white) L     49693        66       1007
1 NFL football (white) XL    79682        74       1198
2 NFL football (white) XS    84943        81       3792
3 NFL football (white) S     78371        73       3974
4 NFL football (blue) L      99482        92       3978
5 NFL football (blue) M      32192        51       3135
6 NFL football (blue XL      75343        71       2879
7 NFL football (red) XXL     84391        79       1192
8 NFL football (red) XS      34727        57       992
9 NFL football (red) L       44993        63       1562

我想做的是创建一个新列,其中包含 'description' 列中字符串末尾的大小(例如 L、Xl、XXL)。

期望的输出:

   description               total      average      number  size
0 NFL football (white) L      49693        66       1007       L
1 NFL football (white) XL    79682        74       1198       XL
2 NFL football (white) XS    84943        81       3792       XS
3 NFL football (white) S     78371        73       3974       S
4 NFL football (blue) L      99482        92       3978       L
5 NFL football (blue) M      32192        51       3135       M
6 NFL football (blue XL      75343        71       2879       XL
7 NFL football (red) XXL     84391        79       1192       XXL
8 NFL football (red) XS      34727        57       992        XS
9 NFL football (red) L       44993        63       1562       L

【问题讨论】:

  • df['size'] = df['description'].str.split().str[-1]
  • 有效吗? df['new_column'] = df['description'].str.split()[-1]

标签: python pandas string multiple-columns


【解决方案1】:

df['size'] = df['description'].str.split().str[-1] – 安德烈亚斯 8 分钟前

谢谢!这做得很完美,非常感谢。

【讨论】:

    猜你喜欢
    • 2015-09-14
    • 2019-06-08
    • 1970-01-01
    • 2019-05-17
    • 2022-08-09
    • 2023-02-05
    • 1970-01-01
    • 1970-01-01
    • 2021-08-15
    相关资源
    最近更新 更多