Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a Pandas dataframe from another column in a dataframe by splitting it?

I have the following source dataframe

Person Country Is Rich?
0 US Yes
1 India No
2 India Yes
3 US Yes
4 US Yes
5 India No
6 US No
7 India No

I need to convert it another dataframe for plotting a bar graph like below for easily accessing data

Bar chart of economic status per country

Data frame to be created is like below.

Country Rich Poor
US 3 1
India 1 3

I am new to Pandas and Exploratory data science. Please help here

like image 696
Vishnu Kaladharan Avatar asked Feb 01 '26 20:02

Vishnu Kaladharan


1 Answers

You can try pivot_table

df['Is Rich?'] = df['Is Rich?'].replace({'Yes': 'Rich', 'No': 'Poor'})
out = df.pivot_table(index='Country', columns='Is Rich?', values='Person', aggfunc='count')
print(out)

Is Rich?  Poor  Rich
Country
India        3     1
US           1     3
like image 109
Ynjxsjmh Avatar answered Feb 04 '26 09:02

Ynjxsjmh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!