Home > other >  Find max of string column by length and assign to other rows of the same column in Pandas
Find max of string column by length and assign to other rows of the same column in Pandas

Time:10-05

I have a pandas column

currency
CNY
CNY,INR
INR

after transform, the output should be

currency
CNY,INR
CNY,INR
CNY,INR

Get the value by max of length and assign to the currency column

CodePudding user response:

Simple. use builtin max with key=len

df['currency'] = max(df['currency'], key=len)

  currency
0  CNY,INR
1  CNY,INR
2  CNY,INR

CodePudding user response:

Find the currency with maximum length:

currency_with_maximum_length = df.currency[df.currency.str.len().idxmax()] # 'CNY,INR'

And assign it to your column:

df['currency'] = currency_with_maximum_length 

Output:

  currency
0  CNY,INR
1  CNY,INR
2  CNY,INR

CodePudding user response:

You can use str.len combined with idxmax:

df['currency'] = df.loc[df['currency'].str.len().idxmax(), 'currency']

output:

  currency
0  CNY,INR
1  CNY,INR
2  CNY,INR

This enables you to easily apply the same logic per group if needed:

g = df['currency'].str.len().groupby(df['group']).idxmax()
df['new_col'] = df['group'].map(g.map(df['currency']))

Example:

  group currency  new_col
0     A      CNY  CNY,INR
1     A  CNY,INR  CNY,INR
2     A      INR  CNY,INR
3     B      XYZ     WXYZ
4     B     WXYZ     WXYZ
5     B      INR     WXYZ
  • Related