如何通过将pandas DataFrame从数据框中的另一列创建pandas DataFrame?

发布于 2025-01-28 21:52:21 字数 916 浏览 2 评论 0原文

我有以下来源数据框架

国家国家富裕?
0美国
1印度
2印度
3我们
4我们
是5印度US 6
6US7
印度我需要将

其转换另一个数据框架,以绘制以下类似的条形图,以便轻松访问数据

每个国家/地区的经济状态图表

要创建的数据框架如下。

国家贫穷的贫穷
美国31
印度13

我是熊猫和探索性数据科学的新手。请在这里帮忙

I have the following source dataframe

PersonCountryIs Rich?
0USYes
1IndiaNo
2IndiaYes
3USYes
4USYes
5IndiaNo
6USNo
7IndiaNo

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.

CountryRichPoor
US31
India13

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

以为你会在 2025-02-04 21:52:21

您可以尝试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

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
变身佩奇 2025-02-04 21:52:21

您可以这样做:

converted = df.assign(Rich=df['Is Rich?'].eq('Yes')).eval('Poor = ~Rich').groupby('Country').agg({'Rich': 'sum', 'Poor': 'sum'})

print(converted)
         Rich  Poor
Country            
India       1     3
US          3     1

但是,如果要将其绘制为barplot,则以下格式可能与绘图库(如 seaborn

plot_df = converted.reset_index().melt(id_vars='Country', value_name='No. of people', var_name='Status')
print(plot_df)
  Country Status  No. of people
0   India   Rich              1
1      US   Rich              3
2   India   Poor              3
3      US   Poor              1

然后,使用seaborn

import seaborn as sns

sns.barplot(x='Country', hue='Status', y='No. of people', data=plot_df)

结果图:

“在此处输入映像”

You could do:

converted = df.assign(Rich=df['Is Rich?'].eq('Yes')).eval('Poor = ~Rich').groupby('Country').agg({'Rich': 'sum', 'Poor': 'sum'})

print(converted)
         Rich  Poor
Country            
India       1     3
US          3     1

However, if you want to plot it as a barplot, the following format might work best with a plotting library like seaborn:

plot_df = converted.reset_index().melt(id_vars='Country', value_name='No. of people', var_name='Status')
print(plot_df)
  Country Status  No. of people
0   India   Rich              1
1      US   Rich              3
2   India   Poor              3
3      US   Poor              1

Then, with seaborn:

import seaborn as sns

sns.barplot(x='Country', hue='Status', y='No. of people', data=plot_df)

Resulting plot:

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文