我可能不太了解何時或如何使用 pandas.DataFrame 的 groupby 函數。在下面的示例中,我想按花瓣長度對我的數據框進行分箱,并計算條目數、每個分箱的平均值和分布。我可以通過三個 groupby 調用來做到這一點,但隨后我在三個單獨的對象中得到了答案。因此,我之后將它們連接起來。現在我有一個對象,但所有列都稱為萼片寬度,將名稱傳遞給 concat 對我不起作用。我也想得到 bin 和平均值,例如用于繪圖,但我不知道該怎么做。import matplotlib.pyplot as pltimport pandas as pdfrom sklearn import datasetsiris = datasets.load_iris()data = pd.DataFrame(iris.data)data.columns = iris.feature_namesdata["bin"] = pd.cut(data["petal length (cm)"], 5)g0 = data.groupby(["bin"])["sepal width (cm)"].count()g1 = data.groupby(["bin"])["sepal width (cm)"].mean()g2 = data.groupby(["bin"])["sepal width (cm)"].std()# how to get better names?g = pd.concat([g0, g1, g2], axis=1)print g# how to extract bin and mean e.g. for plotting?#plt.plot(g.bin, g.mean)
1 回答

拉風的咖菲貓
TA貢獻1995條經驗 獲得超2個贊
關于問題的第二部分,您可以使用字符串操作。
如果我理解正確,你可以使用這個:
a = data['bin']
a1 = a.astype(str).str.strip('([])').str.split(',').str[0].astype(float)
a2 = a.astype(str).str.strip('([])').str.split(',').str[1].astype(float)
data['bin_center'] = (a1+a2)/2
g = data.groupby('bin_center')['sepal width (cm)'].agg(['count', 'mean', 'std'])
plt.plot(g.index, g['mean'])
順便說一句,如果你不想要 bin 中心,并且你想查看帶有 bins 的圖,
你可以使用 dataframe plot:
g = data.groupby('bin')['sepal width (cm)'].agg(['count', 'mean', 'std']) print(g) g['mean'].plot()
添加回答
舉報
0/150
提交
取消