Pandas:基于对其他列应用字符串条件来创建列

2024-07-05 10:18:29 发布

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

我有一个数据帧df,如下所示:

    KPI             Tata    JSW 
Gross Margin %      0.582   0.476   
EBITDA Margin %     0.191   0.23    
EBIT Margin %       0.145   0.183   
SG&A/Revenue        0.141   0.03    
COGS/Revenue        0.418   0.524   
CapE/Revenue        0.0577  0.1204      
ROA                 0.064   0.093   
ROE                 0.138   0.243       
Revenue/Employee $K 290.9   934.4   
Inventory Turnover  2.2     3.27    
AR Turnover         13.02   14.29   
Tot Asset Turnover  0.68    0.74    
Current Ratio       0.9     0.8 
Quick Ratio         0.3     0.4 

我试图添加一个列,例如,scope,基于以下标准:

if df[df['KPI'].str.contains('Margin|Revenue|ROE|ROA')].shape[0] > 0:
  z = 'Max'
elif df[df['KPI'].str.contains('Quick|Current|Turnover')].shape[0] > 0:
  z = 'Min'

换句话说,如果字段KPI包含像RevenueMargin这样的词,那么列scope应该采用Maxelse Min。现在在KPI == COGS/RevenueKPI == CapEx/Revenue中有一个异常。在这种情况下,scope应该取Min,尽管字符串Revenue存在。你知道吗

因此结果df应该如下所示:

Resultant Dataframe

为了达到同样的效果,我正在尝试apply一个字段KPI上的函数。你知道吗

def scope_superlative(col_name):
  df_test = df[df[col_name].str.contains('Margin| Revenue|ROA|ROE')]
  if df_test.shape[0] > 0:
    z = 'Max'
  else:
    df_test = df[df[col_name].str.contains('/Revenue|Current|Quick|Turnover')] ##<-- I want to check if string 'Revenue' is in denominator.##
    if df_test.shape[0] > 0:
      z='Min'
  return z
##Applying this function##
df['scope'] = df.KPI.apply(lambda x : scope_superlative(x))

上面的代码正在生成一个Error作为KeyError: 'Gross Margin %

如果我使用df['scope']=df.apply(scope_superlative('KPI'), axis=1),我会得到一个错误AttributeError: 'DataFrame' object has no attribute 'Max'。你知道吗

有人能帮忙吗?在功能或应用技巧上有什么问题吗?你知道吗


Tags: margintestdfifcurrentminscopekpi
3条回答
  • 可以对所需列使用apply函数。你知道吗
import pandas as pd
import re
d = pd.DataFrame({'a':['a b c','b c d','p q r','d e f','c b a'],'b':[1,2,3,4,5]})

d['scope'] = d['a'].apply(lambda x: 'MAX' if re.search('a|b|e', x) else 'MIN')

d

输出:

      a     b   scope
0   a b c   1   MAX
1   b c d   2   MAX
2   p q r   3   MIN
3   d e f   4   MAX
4   c b a   5   MAX
  • 对于您的数据,这应该是有效的。你知道吗
df['Scope'] = df['KPI'].apply(lambda x: 'MAX' if re.search('Margin| Revenue|ROE|ROA', x) else 'MIN')

对多个条件和值使用^{}

conditions = [
    df['KPI'].str.contains('Margin| Revenue|Revenue/|ROE|ROA'),
    df['KPI'].str.contains('/Revenue|Current|Quick|Turnover')
]
values = ['Max', 'Min']
df['scope'] = pd.np.select(conditions, values, default='Min/Max')

当所有条件都不匹配时,保持default参数为所需的值。你知道吗

或者

如果你只有一个条件

condition = df['KPI'].str.contains('Margin| Revenue|ROE|ROA')
df['scope'] = pd.np.where(condition, 'Max', 'Min')

np.where的第一个参数是条件,第二个是True时要放入的值,第三个是False时要放入的值

我想你在找这样的东西:

import pandas as pd
import re

def fn(row):
    if re.search('/Revenue|Current|Quick|Turnover', row['KPI']):
        return 'Min'
    elif re.search('Margin|Revenue|ROA|ROE', row['KPI']):
        return 'Max'

df = pd.read_csv('so.csv')

df['scope'] = df.apply (lambda row: fn(row), axis=1)
print (df)

这只是使用df.apply()函数,该函数接受每一行并对其应用所提供的函数。你知道吗

对于给定的数据,得出以下结果:

0        Gross Margin %    0.5820    0.4760   Max
1       EBITDA Margin %    0.1910    0.2300   Max
2         EBIT Margin %    0.1450    0.1830   Max
3          SG&A/Revenue    0.1410    0.0300   Min
4          COGS/Revenue    0.4180    0.5240   Min
5          CapE/Revenue    0.0577    0.1204   Min
6                   ROA    0.0640    0.0930   Max
7                   ROE    0.1380    0.2430   Max
8   Revenue/Employee $K  290.9000  934.4000   Max
9    Inventory Turnover    2.2000    3.2700   Min
10          AR Turnover   13.0200   14.2900   Min
11   Tot Asset Turnover    0.6800    0.7400   Min
12        Current Ratio    0.9000    0.8000   Min
13          Quick Ratio    0.3000    0.4000   Min

希望这有帮助!你知道吗

相关问题 更多 >