如何仅提取列的一部分

2024-05-19 20:54:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个如下所示的数据框。我只想保留第3列和第4列的第一个百分比。如何做到这一点。任何帮助都将不胜感激

Metric Group  Metric Type       Tue23rd                      Week24                      
Productive    % Available     83.2%Best Class:D7-92.6%     92.6%Best Class:WD-96.21%
Productive    % Available     85.2%Best Class:A7-98.6%     92.6%Best Class:LD-95.21%
Productive    % Available     89.2%Best Class:D7-94.6%     92.6%Best Class:WD-93.21%   

预期输出是这样的

Metric Group    Metric Type       Tue23rd          Week24                      
Productive     % Available        83.2%             92.6%
Productive     % Available        85.2%             92.6%
Productive     % Available        89.2%             92.6%      

Tags: 数据typegroupmetricclassavailablebest百分比
3条回答

您可以使用regex使用内置的pd.Series.str.extract方法:

df["Tue23rd"].str.extract("([0-9\.%]+)Best")

请用这个str.replace()紧跟在{}之后的任何{}和{}。比光环稍微快一点

 df=df.apply(lambda x: x.str.replace('((?<=\d[%])([\w\D]+))',''))



 Metric Group  Metric Type Tue23rd Week24
0   Productive  % Available   83.2%  92.6%
1   Productive  % Available   85.2%  92.6%

您可以尝试:

pattern = '^([\d\.%]+)'

for col in df.columns[2:]:
    df[col] = df[col].str.extract(pattern)[0]

输出:

  Metric Group  Metric Type Tue23rd Week24
0   Productive  % Available   83.2%  92.6%
1   Productive  % Available   85.2%  92.6%
2   Productive  % Available   89.2%  92.6%

相关问题 更多 >