我有如下数据框

d = {'Name':['Alisa','Bobby','jodha','jack','raghu','Cathrine',
'Alisa','Bobby','kumar','Alisa','Alex','Cathrine'],
'Age':[26,24,23,22,23,24,26,24,22,23,24,24],
'Score':[85,63,55,74,31,77,85,63,42,62,89,77]}

df = pd.DataFrame(d,columns=['Name','Age','Score'])
Name    Age     Score
0   Alisa   26  85
1   Bobby   24  63
2   jodha   23  55
3   jack    22  74
4   raghu   23  31
5   Cathrine    24  77
6   Alisa   26  85
7   Bobby   24  63
8   kumar   22  42
9   Alisa   23  62
10  Alex    24  89
11  Cathrine    24  77

当我运行下面的代码时,它运行得很好,并获得如图所示的输出。为每个列创建一个新列。
a=df.columns[1:]
df[a +'rat'] = df[a]/df[a].sum()
Name    Age     Score   Agerat  Scorerat
0   Alisa   26  85  0.091228    0.105853
1   Bobby   24  63  0.084211    0.078456
2   jodha   23  55  0.080702    0.068493
3   jack    22  74  0.077193    0.092154
4   raghu   23  31  0.080702    0.038605
5   Cathrine    24  77  0.084211    0.095890
6   Alisa   26  85  0.091228    0.105853
7   Bobby   24  63  0.084211    0.078456
8   kumar   22  42  0.077193    0.052304
9   Alisa   23  62  0.080702    0.077210
10  Alex    24  89  0.084211    0.110834
11  Cathrine    24  77  0.084211    0.095890


但是,当我想用下面的代码a为每个列创建一个Min时,我会得到错误"KeyError: "None of [Index(['Agemin', 'Scoremin'], dtype='object')] are in the [columns]"。我想让它创建那个专栏!
df[a +'min'] = df[a].min()

那么,我们如何为每个列创建min()max()sum()等列,而不必指定每个列的名称?

最佳答案

可以使用assign传递参数,从序列中**多个标量值。索引成为列名,值广播到所有行。对于序列add_suffix添加到索引,而稍后我使用它添加到列名,这是数据帧的行为方式。

import pandas as pd

df1 = df.select_dtypes('number')

df = df.assign(**df1.min().add_suffix('min'))
#        Name  Age  Score  Agemin  Scoremin
#0      Alisa   26     85      22        31
#1      Bobby   24     63      22        31
#2      jodha   23     55      22        31
...
#10      Alex   24     89      22        31
#11  Cathrine   24     77      22        31

就我个人而言,另一个结果是:
df = pd.concat([df, (df1/df1.sum()).add_suffix('rat')], axis=1)

#        Name  Age  Score  Agemin  Scoremin    Agerat  Scorerat
#0      Alisa   26     85      22        31  0.091228  0.105853
#1      Bobby   24     63      22        31  0.084211  0.078456
#2      jodha   23     55      22        31  0.080702  0.068493
#...
#10      Alex   24     89      22        31  0.084211  0.110834
#11  Cathrine   24     77      22        31  0.084211  0.095890

关于python - 在列上复写并为每个列创建min()列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57847356/

10-12 17:00