簡體   English   中英

為 dataframe 中的不同行組繪制不同的線?

[英]Plotting different lines for different groups of rows in a dataframe?

我的 dataframe 看起來像這樣:

在此處輸入圖像描述

如何使用 pandas 和 plotly 后端生成一個包含兩條線的單一時間序列圖,一條用於 Ankit,一條用於 John?

這是在屏幕截圖中生成 dataframe 的代碼:

import pandas
pandas.options.plotting.backend = "plotly"

details = { 
    'Name' : ['Ankit', 'John', 'Ankit', 'John', 'John', 'John', 'Ankit', 'Ankit'], 
    'Month': ['January', 'January', 'February', 'February', 'March', 'April', 'March', 'April'],
    'Grade' : [9, 8, 7, 10, 8, 9, 8, 10], 
} 
d = pandas.DataFrame(details)
d = d.groupby(['Name', 'Month'], as_index=False)['Grade'].mean()
print(d)

如果我這樣做:

d.plot(x='Month', y='Grade')

這將產生一行不區分 Ankit 和 John 的行。

d = d.pivot(index='Month', columns='Name', values='Grade')
d.plot()

在您的groupby代碼更改順序和Series.unstack的聚合mean中:

d = pandas.DataFrame(details)
df = d.groupby(['Month','Name'])['Grade'].mean().unstack()

df.plot()

或使用DataFrame.pivot_table

d = pandas.DataFrame(details)
df = d.pivot_table(index='Month', columns='Name', values='Grade', aggfunc='mean')

df.plot()

暫無
暫無

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

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