![](/img/trans.png)
[英]How to create a new column in a Pandas DataFrame based on a column in another DataFrame?
[英]How to create a Pandas dataframe from another column in a dataframe by splitting it?
我有以下源數據框
人 | 國家 | 有錢嗎? |
---|---|---|
0 | 我們 | 是的 |
1 | 印度 | 不 |
2 | 印度 | 是的 |
3 | 我們 | 是的 |
4 | 我們 | 是的 |
5 | 印度 | 不 |
6 | 我們 | 不 |
7 | 印度 | 不 |
我需要將其轉換為另一個數據框以繪制如下所示的條形圖,以便輕松訪問數據
要創建的數據框如下所示。
國家 | 富有的 | 較差的 |
---|---|---|
我們 | 3 | 1 |
印度 | 1 | 3 |
我是 Pandas 和探索性數據科學的新手。 請在這里幫忙
你可以試試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
你可以這樣做:
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
但是,如果要將其繪制為條形圖,則以下格式可能最適合使用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)
結果圖:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.