簡體   English   中英

寬幅 CSV 與 Plotly 快遞

[英]Wide format CSV with Plotly Express

我有一個寬的 csv 文件,其中第一列是日期(以Ymd格式)和以下列,標題是不同的 covid19 相關指標,如本例所示:

數據 casos_novos_t casos_novos_d obitos_t obitos_d
2021-21-04 123000 12000 34000 345
2021-22-04 134000 14000 34505 567

等等。 樣本數據集可以在這里找到

我在 Python 中有以下代碼:

# Import Libraries

import pandas as pd 
import plotly.express as px 

# Read CSV file 

df = pd.read_csv("covid19pt_data.csv")

# Plot

fig = px.bar(df)

fig.show()

運行它后,我收到以下錯誤消息:

ValueError: Plotly Express 無法處理具有不同類型列的寬格式數據

如果我將代碼更改為

fig = px.bar(df, x='data',y='novos_casos_t')

fig.show()

該代碼有效,向我展示了該列的條形圖。 任何其他列也是如此。

但是,在閱讀了這篇文章后,我的印象是 plotly 現在支持寬格式框架,所以我不明白我明顯做錯了什么。

我的經驗水平接近於零,非常感謝任何幫助我了解我做錯了什么的幫助。

如果您向下滾動到Plotly 中的 Wide-Form Defaults 部分,他們解釋說,如果您沒有為px.bar方法提供參數xy ,那么默認行為是將 x 設置為df.index和 y到df.columns 但是,您的 DataFrame 未按日期索引,並且您的日期列data是 df.columns 中的第一列

如果我們查看您的df.dtypes的 df.dtypes:

data             object
casos_novos_t     int64
casos_novos_d     int64
obitos_d          int64
obitos_t          int64
d_internados      int64
d_uci             int64
recuperados_t     int64
recuperados_d     int64
vigilancia_t      int64
vigilancia_d      int64
ativos_t          int64
ativos_d          int64

我們可以看到列的數據類型不同,因為data列是object類型,而其他列是int64 ,並且由於 df.columns 默認傳遞給y參數,這就是導致 Plotly express 拋出的原因ValueError: Plotly Express cannot process wide-form data with columns of different type

如果要將此默認行為用於 plot 條形圖中data列的所有數字列,則可以使用df = df.set_index('data')將 DataFrame 的索引設置為data列。 這可確保 DataFrame 中的其余列具有相同的int64類型。

# Import Libraries

import pandas as pd 
import plotly.express as px 

# Read CSV file 

df = pd.read_csv("covid19pt_data.csv")

## set the index as the data column
## all of the remaining columns are now of the same int64 type
df = df.set_index('data')

# Plot
fig = px.bar(df)

fig.show()

在此處輸入圖像描述

暫無
暫無

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

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