NSN
NSN

Reputation: 750

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

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

Upvotes: 1

Views: 56

Answers (3)

mozway
mozway

Reputation: 261860

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

Upvotes: 0

T C Molenaar
T C Molenaar

Reputation: 3260

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

Upvotes: 1

Shubham Sharma
Shubham Sharma

Reputation: 71687

Simple. use builtin max with key=len

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

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

Upvotes: 1

Related Questions