简体   繁体   English

在 pandas 中递增列标题

[英]Incrementing column headers in pandas

Could you please help me to solve the below issue.您能帮我解决以下问题吗?

From the initial data frame given below, I want to create a new data frame based on a column condition like this:从下面给出的初始数据框中,我想根据这样的列条件创建一个新的数据框:

if mean > median, add 1 to A & -1 to B, elif mean < median, add -1 to A & 1 to B, else add 0 to both A and B.

Initial Data Frame:初始数据框:

    A/B     A/C     A/D     B/C     B/D     C/D
0   0.75    0.61    1.07    0.82    1.43    1.75
1   1.21    10.88   2.17    9       1.8     0.2
2   0.95    0.85    1.97    0.9     2.08    2.32
3   0.47    0.47    0.91    1       1.94    1.94

平均值和中位数

Then final output data frame should consist of total score of all elements like below:然后最终的 output 数据帧应该包括所有元素的总分,如下所示:

输出数据框

Thanking you in advance.提前谢谢你。

Use:利用:

#count mean and median
df1 = df.agg(['mean','median']).round(2)
#difference in sample data so set 0.85
df1.loc['mean', 'A/B'] = 0.85

First transpose DataFrame and split index to MultiIndex by str.split :首先转置 DataFrame 并通过str.splitindex拆分为MultiIndex

df1 = df1.T
df1.index = df1.index.str.split('/', expand=True)

Then compare mean with median and set new 2 columns in numpy.select :然后将meanmedian进行比较,并在numpy.select中设置新的 2 列:

m1 = df1['mean'].gt(df1['median']).to_numpy()[:, None]
m2 = df1['mean'].eq(df1['median']).to_numpy()[:, None]

df1 = pd.DataFrame(np.select([m1, m2], [[1,-1], [0,0]], [-1, 1]),
                   index=df1.index,
                   columns=['a','b'])
print (df1)
      a  b
A B   0  0
  C   1 -1
  D   1 -1
B C   1 -1
  D  -1  1
C D  -1  1

Last use sum per both index and join together:最后使用每个索引的sum并连接在一起:

df2 = (pd.concat([df1.a.droplevel(1), df1.b.droplevel(0)])
         .sum(level=0)
         .rename_axis('Element')
         .reset_index(name='Total Score'))
print (df2)
  Element  Total Score
0       A            2
1       B            0
2       C           -3
3       D            1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM