我有以下数据框:
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
我正在尝试创建一个新的数据框,其中每个流派都是一个单独的列,以便我可以将数据放入箱线图中。我该怎么做?预期结果应类似于:
Platform Racing Sports
0 29.08 15.85 41.49
1 0.01 0.00 15.75
对于原始数据帧中列出的每个流派,预期的数据帧应该有一个值(16599 个值)
答案 0 :(得分:0)
您可以使用 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()
答案 1 :(得分:0)
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
要显示箱线图,您可以简单地从 .boxplot()
调用 agg_data
即
agg_data.boxplot()
plt.show()
seaborn
库来显示箱线图,而无需聚合数据(seaborn
可以轻松为您处理)例如import seaborn as sns
sns.barplot(data=df, x='Genre', y='NA_Sales')
plt.show()