簡體   English   中英

Pandas 按列和均值散點圖對 Excel 數據進行分組

[英]Pandas group Excel data by column and Graph Scatter Plot With Mean

我從幾個 Excel 文件中讀取了一組數據。 我可以使用 Pandas 輕松讀取、合並和分組數據。 我對數據有兩列感興趣,“產品類型”和“測試持續時間”。

包含從 Excel 文件讀取的數據的數據框稱為 oData。

oDataGroupedByProductType = oData.groupby(['Product Type'])

我已經使用 plotly 繪制如下圖,但 plotly 不會將數據保密,如果我希望數據保密,我必須付費。 付費不是一種選擇。 在此處輸入圖片說明 如何使用 Pandas 和/或 matplotlib 制作相同的圖形,同時還顯示每種產品類型的平均值?

正如Bound所說,你可以用stripplot做幾行(seaborn 文檔頁面的示例)。

import seaborn as sns
sns.set_style("whitegrid")
tips = sns.load_dataset("tips") # load some sample data
ax = sns.stripplot(x="day", y="total_bill", data=tips)

在此處輸入圖片說明

假設你有一些數據框:

In [4]: df.head(20)
Out[4]:
   product      value
0        c   5.155740
1        c   8.983128
2        c   5.150390
3        a   8.379866
4        c   8.094536
5        c   7.464706
6        b   3.690430
7        a   5.547448
8        a   7.709569
9        c   8.398026
10       a   7.317957
11       b   7.821332
12       b   8.815495
13       c   6.646533
14       c   8.239603
15       c   7.585408
16       a   7.946760
17       c   5.276864
18       c   8.793054
19       b  11.573413

您需要有一個產品的數值來繪制它,所以快速而干燥,只需通過映射數值創建一個新列:

In [5]: product_map = {p:r for p,r in zip(df['product'].unique(), range(1, df.values.shape[0]+1))}

In [6]: product_map
Out[6]: {'a': 2, 'b': 3, 'c': 1}

當然,有很多方法可以實現這一點......

現在,創建一個新列:

In [8]: df['product_code'] = df['product'].map(product_map)

In [9]: df.head(20)
Out[9]:
   product      value  product_code
0        c   5.155740             1
1        c   8.983128             1
2        c   5.150390             1
3        a   8.379866             2
4        c   8.094536             1
5        c   7.464706             1
6        b   3.690430             3
7        a   5.547448             2
8        a   7.709569             2
9        c   8.398026             1
10       a   7.317957             2
11       b   7.821332             3
12       b   8.815495             3
13       c   6.646533             1
14       c   8.239603             1
15       c   7.585408             1
16       a   7.946760             2
17       c   5.276864             1
18       c   8.793054             1
19       b  11.573413             3

現在,使用plot中的輔助方法pandas基本上是圍繞一個包裝matplotlib

In [10]: df.plot(kind='scatter', x = 'product_code', y = 'value')
Out[10]: <matplotlib.axes._subplots.AxesSubplot at 0x12235abe0>

和輸出:

在此處輸入圖片說明

顯然,這是快速而骯臟的,但它應該讓你繼續前進......

如果其他人有非常相似的問題並希望看到最終結果,我最終使用了 seaborn,如下所示:

import seaborn as sns
import matplotlib.pyplot as plt
...
sns.set_style("whitegrid")
sns.boxplot(x=oData['Product Type'],
          y=oData['Test Duration?'],
          data=oData)
plt.savefig('Test Duration vs. Product Type.png')

圖表如下。 出於隱私原因,我模糊了圖表上的產品標簽。

在此處輸入圖片說明

暫無
暫無

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

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