1

I have a csv file which I am reading through pandas

Here's my code

import pandas as pd
df=pd.read_csv(filename.csv)
x=100*df['Country'].value_counts(normalize=True).to_frame()
print(x)

Here's my output

Country
US
France
Germany

I want to save this output in a new column in the existing dataframe .How can I do that?

1
  • Your output is missing the counts, what actually do you want to assign? Do you want df['new'] = df.groupby('Country').transform('count')? or df['Country'].map(100*df['Country'].value_counts(normalize=True)) Commented May 17, 2023 at 9:56

2 Answers 2

1

Use Series.map:

df['new'] = df['Country'].map(100*df['Country'].value_counts(normalize=True))

Sample:

df = pd.DataFrame({'Country':['US','US','France','US']})

df['new'] = df['Country'].map(100*df['Country'].value_counts(normalize=True))
print (df)
  Country   new
0      US  75.0
1      US  75.0
2  France  25.0
3      US  75.0
Sign up to request clarification or add additional context in comments.

Comments

0

I hope, it works for your solution

import pandas as pd
df=pd.read_csv('countries.csv')
df['New Col'] = 100*df['Country'].value_counts(normalize=True).values
df

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.