0

The objective is to create a new multiindex column (stat) based on the condition of the column (A and B)

Condition for A

CONDITION_A='n'if A<0 else 'p'

and

Condition for B

CONDITION_B='l'if A<0 else 'g'

Currently, the idea is to separately analyse condition A and B, and combine the analysis to obtain the column stat as below, and finally append back to the main dataframe.

However, I wonder whether there is a way to maximise the line of code to achieve similar objective

The expected output

enter image description here

import pandas as pd
import numpy as np

np.random.seed(3)
arrays = [np.hstack([['One']*2, ['Two']*2]) , ['A', 'B', 'A', 'B']]
columns = pd.MultiIndex.from_arrays(arrays)
df=  pd.DataFrame(np.random.randn(5, 4), columns=list('ABAB'))

df.columns = columns
idx = pd.IndexSlice
mask_1 = df.loc[:,idx[:,'A']]<0
appenddf=mask_1.replace({True:'N',False:'P'}).rename(columns={'A':'iii'},level=1)


mask_2 = df.loc[:,idx[:,'B']]<0
appenddf_2=mask_2.replace({True:'l',False:'g'}).rename(columns={'A':'iv'},level=1)

# combine the multiindex
stat_comparison=[''.join(i) for i in zip(appenddf["iii"],appenddf_2["iv"])]

1 Answer 1

1

You can try concatinating both df's:

s=pd.concat([appenddf,appenddf_2],axis=1)
cols=pd.MultiIndex.from_product([s.columns.get_level_values(0),['stat']])
out=pd.concat([s.loc[:,(x,slice(None))].agg('_'.join,axis=1) for x in s.columns.get_level_values(0).unique()],axis=1,keys=cols)

output of out:

    One     Two
    stat    stat
0   P_g     P_l
1   N_l     N_l
2   N_l     N_g
3   P_g     P_l
4   N_l     P_l
Sign up to request clarification or add additional context in comments.

2 Comments

This is great. But It will be a bonus for future reader if you can append this result to the original df as depicted in the figure.
@balandongiv use df=pd.concat([df,out],axis=1).sort_index(axis=1)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.