簡體   English   中英

如何在 excel 中讀取第一列及其值作為 Pandas 數據框中的列名

[英]How to read the first column with its values in excel as a columns names in pandas data frame

所以首先我有一個包含很多工作表的 Excel 文件,現在有一些工作表看起來像這樣:

|    Date    | 11-12-2019  | 12-12-2019   | 13-12-2019 | 14-12-2019  | 15-12-2019   |
|:-----------|------------:|:------------:|:-----------|------------:|:------------:|
| Col_1      |    1111     |     2222     | 3333       |        4444 |     5555     |
| Col_2      |    1111     |     2222     | 3333       |        4444 |     5555     |
| Col_3      |    1111     |     2222     | 3333       |        4444 |     5555     |
| Col_4      |    1111     |     2222     | 3333       |        4444 |     5555     |
| Col_5      |    1111     |     2222     | 3333       |        4444 |     5555     |
| Col_6      |    1111     |     2222     | 3333       |        4444 |     5555     |

我想用熊貓數據框使它成為這樣的:

|    Date    |    Col_1    |     Col_2    | Col_3      |   Col_4     |     Col_5    |     Col_5    |
|:-----------|------------:|:------------:|:-----------|------------:|:------------:|:------------:|
| 11-12-2019 |    1111     |     1111     | 1111       |    1111     |     1111     |     1111     |
| 12-12-2019 |    2222     |     2222     | 2222       |    2222     |     2222     |     2222     |
| 13-12-2019 |    3333     |     3333     | 3333       |    3333     |     3333     |     3333     |
| 14-12-2019 |    4444     |     4444     | 4444       |    4444     |     4444     |     4444     |
| 15-12-2019 |    5555     |     5555     | 5555       |    5555     |     5555     |     5555     |

那么是否可以使用 python pandas 或任何其他庫來做到這一點?

我們可以使用Transpose (與DataFrame.T相同)來做到這一點。 然后使用DataFrame.iloc用第一行替換列名:

dft = df.T                  # transpose dataframe
dft.columns = dft.iloc[0]   # replace columns, by values in first row
dft = dft.iloc[1:]          # remove first row.
Date       Col_1 Col_2 Col_3 Col_4 Col_5 Col_6
11-12-2019  1111  1111  1111  1111  1111  1111
12-12-2019  2222  2222  2222  2222  2222  2222
13-12-2019  3333  3333  3333  3333  3333  3333
14-12-2019  4444  4444  4444  4444  4444  4444
15-12-2019  5555  5555  5555  5555  5555  5555

你也可以使用df.swapaxes

>>> df.set_index('Date').swapaxes(1,0)

Date        Col_1  Col_2  Col_3  Col_4  Col_5  Col_6
11-12-2019   1111   1111   1111   1111   1111   1111
12-12-2019   2222   2222   2222   2222   2222   2222
13-12-2019   3333   3333   3333   3333   3333   3333
14-12-2019   4444   4444   4444   4444   4444   4444
15-12-2019   5555   5555   5555   5555   5555   5555

您可以使用 Python 庫/Excel 插件 xlwings 執行此操作。 代碼將是這樣的:

import xlwings as xw
sht = xw.Book().sheets[0]
pd_df = sht.range('reference to cells with data').options(transpose = True, pd.DataFrame, index = True, header = True).value

暫無
暫無

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

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