簡體   English   中英

讀取 header 包含 Python pandas 中的日期

[英]Reading header containing dates in Python pandas

我有一張 excel 表:

  31-12-2019  31-01-2020  28-02-2020 *(which btw is formatted as: 31-Dec-19, 31-Jan-20, etc. not sure if relevant)* 
1  -0,36%       0,12%      -0,09%
2  -0,18%       0,06%      -0,07%
3   0,05%       0,04%       0,14%

需要明確的是,問題不在於讀取文件,而在於下面的問題。

我想在 python 中使用 pandas 讀取此文件,並將 header 中的日期作為字符串 這樣以后我就可以使用 df['31-12-2019'] 之類的內容來引用任何列。

當我現在閱讀 excel 時,我收到一條 keyerror 消息,因為 header 中的日期格式已更改。 我現在是這樣讀的:

curve = pd.read_excel("Monthly curves.xlsx", sheet_name = "swap", skiprows = 1, index_col = 0)

選擇例如列 31-12-2019 時收到錯誤消息:“Keyerror:'31-12-2019'。任何幫助將不勝感激!

另外,第一列沒有 header,我自己如何將其命名為“年”?

當我使用它時它起作用了:

import pandas as pnd

file = 'excelfile.xlsx'
df = pnd.read_excel(file,sheet_name=0,index_col=0)
df.head()

我不知道如何命名標題...

我通過閱讀以下文件來解決我的問題:

curve = pd.read_excel("Monthly Curves.xlsx", sheet_name = "swap", index_col = 0, skiprows = 2, header = None)

然后到 select 例如我使用的第 91 列 .loc (因為不推薦使用 .ix ),我通過以下方式做到了:

M12 = curve.loc[:, 91]

希望對其他人也有幫助!

暫無
暫無

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

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