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?

mozway
  • 194,879
  • 13
  • 39
  • 75
  • 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))` – mozway May 17 '23 at 09:56

2 Answers2

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
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
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
Muhammad Ali
  • 444
  • 7