[英]python: creating a new dataframe from the averages of a filtered dataframe
[英]Creating new dataframe from filtered column of a dataframe
我有以下 dataframe:
Genre NA_Sales
0 Sports 41.49
1 Platform 29.08
2 Racing 15.85
3 Sports 15.75
4 Role-Playing 11.27
... ... ...
16594 Shooter 0.01
16595 Racing 0.00
16596 Puzzle 0.00
16597 Platform 0.01
16598 NaN NaN
我正在嘗試創建一個新的 dataframe ,其中每個流派都是一個單獨的列,以便我可以將數據放入箱線圖中。 我該怎么做? 預期結果應類似於:
Platform Racing Sports
0 29.08 15.85 41.49
1 0.01 0.00 15.75
對於原始 dataframe 中列出的每個類型,預期的 dataframe 應該有一個值(16599 個值)
您可以使用pivot
方法從長到寬 pivot 您的數據幀。
import numpy as np
from itertools import cycle
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.pyplot
genres = cycle(['Sports', 'Platform', 'Racing', 'Sports', 'Role-Playing', 'Shooter', 'Racing', 'Puzzle', 'Platform'])
# Initialise sample data
data = {'Genre': [next(genres) for genre in range(0, 1000)],
'NA_Sales': np.random.randint(0, 50, size = 1000)}
# # Create DataFrame
df = pd.DataFrame(data)
# Pivot the data frame from long to wide
df = df.pivot(values='NA_Sales', columns='Genre')
# Create the boxplot
cols = ['Sports', 'Platform', 'Racing', 'Sports', 'Role-Playing', 'Shooter', 'Racing', 'Puzzle', 'Platform']
df.boxplot(column=cols, rot = 90)
plt.show()
boxplot
進行可視化,因此您首先需要在顯示 boxplot 之前聚合數據框。 您可以簡單地使用pandas.pivot_table()
方法進行轉換,並使用.boxplot()
方法顯示boxplot
。 默認情況下, pandas.pivot_table()
中使用的聚合方法是'mean'
但您可以通過更改aggfunc
參數的默認值來更改它,例如example = df.head()
example
Genre NA_Sales
0 Sports 41.49
1 Platform 29.08
2 Racing 15.85
3 Sports 15.75
4 Role-Playing 11.27
agg_data = pd.pivot_table(example, values='NA_Sales', columns='Genre', aggfunc='sum')
agg_data
Genre Platform Racing Role-Playing Sports
NA_Sales 29.08 15.85 11.27 17.24
要顯示箱線圖,您可以簡單地從agg_data
調用.boxplot()
即
agg_data.boxplot()
plt.show()
seaborn
庫來顯示箱線圖而無需匯總數據( seaborn
可以輕松為您處理)例如import seaborn as sns
sns.barplot(data=df, x='Genre', y='NA_Sales')
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.