Home > database >  Panda merge all columns start with a prefix "result"
Panda merge all columns start with a prefix "result"

Time:01-11

I have a dynamic dataframe generation which create column or columns like below x,y,z, can be anything

df

   result  result_x  result_y  result_z  result_.....        
    0       1          1             0              
    0       1          0             1              

some times it will generate

   result  result_x          
    0       1                      
    0       1          

Some time it will generate

   result  result_x  result_y         
    0       1           1           
    0       1           2

some time it can generate

   result  result_x  result_y result_z result_a result_b......any number of result         
    0       1           1           
    0       1           2

I want a simple dataframe which will merge all columns start prefix with result

it would be output of first df:

result
0110.. #merge all columns value
0101...

Note:

I have other columns as well in df

like

username,address,xapi_data,...,result,result_x,result_y,...

CodePudding user response:

You can use .str.startswith:

result_cols = df.columns.str.startswith('result')

(df.loc[:, result_cols]               # extract result columns
   .astype(str).agg(''.join, axis=1)  # join them
   .to_frame('result').join(df.loc[:, ~result_cols]) # join the other columns
)
  • Related