簡體   English   中英

為分組的 pandas dataframe 創建散點圖

[英]Creating a scatterplot for a grouped pandas dataframe

我有一個 Pandas DataFrame 我想按某個列分組。 之后,我想制作這個分組的 dataframe 的散點圖。 但是,如果我這樣做,我會收到一個錯誤,因為我分組的列無法識別。

# Data loading, processing and for more
import pandas as pd
import numpy as np

# Visualization
import seaborn as sns
import matplotlib.pyplot as plt
# set seaborn style because it prettier
sns.set()

df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))

df2 = df.groupby(['A']).agg({'D':sum})
df2.plot.scatter(x='A', y='D')

我將如何創建這樣的散點圖?

您需要在groupby之后重置索引。

import pandas as pd
import numpy as np

# Visualization
import seaborn as sns
import matplotlib.pyplot as plt
# set seaborn style because it prettier
sns.set()

df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))

df2 = df.groupby(['A']).agg({'D':sum})
df2.reset_index(inplace=True)
df2.plot.scatter(x='A', y='D')

執行 groupby 操作時,默認情況下執行 groupby 的列成為索引。 在 groupby 之后的上述情況下,如果您檢查 df2,它的結構將是這樣的:

In [2]: df2                                                                                                                                                                     
Out[2]: 
      D
A      
0   180
1    29
2    52
3    39
4    91
..  ...
93   56
94   17
96   47
98  125
99  214

[61 rows x 1 columns]

要訪問 A 列,您需要使用reset_index將索引設為單獨的列。

您不能將A設置為groupby中的索引:

# notice the difference `sum` and `'sum'`
# the later is vectorized
df2 = df.groupby(['A'], as_index=False).agg({'D':'sum'})

df2.plot.scatter(x='A', y='D')

或者您可以保留您的代碼並使用plt.scatter

df2 = df.groupby(['A']).agg({'D':'sum'})
plt.scatter(df2.index, df2['D'])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM