gpt4 book ai didi

python-3.x - 用 % 在数字上拆分 Pandas 列

转载 作者:行者123 更新时间:2023-12-04 08:45:51 25 4
gpt4 key购买 nike

我有一个 df,其中一列显示如下:

**Share**
We are safe 25%
We are always safe 12.50% (India Aus, West)
We are ok (USA, EU)
We are not OK
What is this
Always wise 25.66%
我想拆分此列,以便将适用的 % 值从该列拆分为一个新的列。
所以输出将是
Share                  Percent    LOCATION
We are safe 25%
We are always safe 12.50% India Aus, West
We are ok USA, EU
We are not OK
What is this
Always wise 25.66%
我认为下面会从右边拆分它,但它不起作用
df['Percent'] = df['Share'].str.rsplit(r' \d',1).str[0]

最佳答案

您可以提取这些值:

df[['Share','Percent']] = df['Share'].str.split(r'\s+(?=\d+(?:\.\d+)?%\s*$)',expand=True).fillna("")
Pandas 测试:
import pandas as pd
df = pd.DataFrame({'Share':['We are safe 25%','We are ok', 'We are always safe 12.50%']})
df[['Share','Percent']] = df['Share'].str.split(r'\s+(?=\d+(?:\.\d+)?%\s*$)',expand=True).fillna("")
>>> df
Share Percent
0 We are safe 25%
1 We are ok
2 We are always safe 12.50%
regex demo .细节:
  • \s+ - 一个或多个空格
  • (?=\d+(?:\.\d+)?%\s*$) - 匹配一个位置的正向前瞻,紧跟其后的是:
  • \d+ - 一位或多位数字
  • (?:\.\d+)? - 可选序列 .和一位或多位数字
  • % - 一个 %符号
  • \s* - 0 个或多个尾随(如 $ 紧随其后)空格和
  • $ - 字符串的结尾。

  • 关于python-3.x - 用 % 在数字上拆分 Pandas 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64334963/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com