Skip to content Skip to sidebar Skip to footer

Conditional Split On Creating New Columns Using Pandas

I have a data where in column 'Type', I have set of currencies. I created new columns based on these currencies. But i am not sure how to give a condition like if the type is btc t

Solution 1:

You can loop by unique values and create difference to new columns created by f-strings:

for v in df['Type'].unique():
    df[f'changbtwread_{v}'] = df.loc[df['Type'].eq(v), 'Last'].diff()
print (df)
  Type     Last  changbtwread_ada  changbtwread_btc  changbtwread_eur
0  ada  3071.56               NaN               NaN               NaN
1  ada  3097.82             26.26               NaN               NaN
2  btc  1000.00               NaN               NaN               NaN
3  ada  2000.00          -1097.82               NaN               NaN
4  btc  3000.00               NaN            2000.0               NaN
5  eur  1000.00               NaN               NaN               NaN
6  eur  1500.00               NaN               NaN             500.0

Post a Comment for "Conditional Split On Creating New Columns Using Pandas"