簡體   English   中英

如何在熊貓的多維列表中設置列和行索引

[英]How do I set the column and row indexes on a multidimensional list in pandas

我有一組要從Google工作表中檢索的數據。 它以以下格式返回:

[['Incident Severity', '# of Incidents by Severity'], ['Sev 1', '0'], ['Sev 2', '0'], ['Sev 3', '3'], ['Sev 4', '2']]

我已使用from_records將其導入到Pandas中,使用df.head()給了我以下內容:

                   0                           1
0  Incident Severity  # of Incidents by Severity
1              Sev 1                           0
2              Sev 2                           0
3              Sev 3                           3
4              Sev 4                           2

但是,第一行需要設置為標題,第一列應該為索引。 我設法通過執行以下操作來更改列標題:

df.columns = df.iloc[0]
df = df.reindex(df.index.drop(0))

這給了我:

0 Incident Severity # of Incidents by Severity
1             Sev 1                          0
2             Sev 2                          0
3             Sev 3                          3
4             Sev 4                          2

如何刪除第一個索引列,以便得到下表:

Incident Severity # of Incidents by Severity
            Sev 1                          0
            Sev 2                          0
            Sev 3                          3
            Sev 4                          2

我對熊貓和數據框還很陌生,所以如果我遺漏了一些明顯的東西,請原諒我。 我試圖用谷歌搜索它,但沒有找到我需要知道的!

使用列表的索引創建DataFrame

L = [['Incident Severity', '# of Incidents by Severity'],
      ['Sev 1', '0'],
      ['Sev 2', '0'], 
      ['Sev 3', '3'], 
      ['Sev 4', '2']]

df = pd.DataFrame(L[1:], columns=L[0])
print (df)

  Incident Severity # of Incidents by Severity
0             Sev 1                          0
1             Sev 2                          0
2             Sev 3                          3
3             Sev 4                          2

無法刪除索引,一種解決方案(確實很糟糕)是將索引轉換為空值:

df.index = [''] * len(df)
print (df)
 Incident Severity # of Incidents by Severity
             Sev 1                          0
             Sev 2                          0
             Sev 3                          3
             Sev 4                          2

但是,如果需要將沒有索引的DataFrame寫入文件,請向to_csv添加參數index=False

print (df.to_csv(index=False))
Incident Severity,# of Incidents by Severity
Sev 1,0
Sev 2,0
Sev 3,3
Sev 4,2

暫無
暫無

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

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