简体   繁体   中英

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:

输出数据框

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 :

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

Then compare mean with median and set new 2 columns in numpy.select :

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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