python - 如何使用 DataFrame 中的行值作为 Pandas 中的操作列?

标签 python pandas jupyter-notebook

我有一个数据库,其中第一行是年份,第一列是每个系列的类别。我想知道如何反转它?

Unnamed=0          2001 2002 2003

General             456  567  543
Cleaning            234  234  344

是否可以有一个列日期和每列包含我需要的变量?

Date       General    Cleaning

2001         456          234
2002         567          234
2003         543          344  

最佳答案

您需要 T 进行转置,然后需要 rename_axis 到新列名称,最后需要 reset_index :

df = df.T.rename_axis('Date').reset_index()
print (df)
   Date  General  Cleaning
0  2001      456       234
1  2002      567       234
2  2003      543       344

如果需要第一列作为索引:

df = df.T.rename_axis('Date')
print (df)
      General  Cleaning
Date                   
2001      456       234
2002      567       234
2003      543       344
<小时/>
df = df.T.rename_axis(None)
print (df)
      General  Cleaning
2001      456       234
2002      567       234
2003      543       344

关于python - 如何使用 DataFrame 中的行值作为 Pandas 中的操作列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43698202/

相关文章:

python - 有没有办法在 Python-Pandas 中多重过滤 Dataframe?

python-3.x - Anaconda 4.3,64 位(python 3.6),在 Windows 开始菜单中留下不正确的截断路径

python - 如何从数据框制作 3D 条形图

python - 如何在本地运行时安装 Google colab?

python - 使用 MySQL 进行数据操作 - 连接和计数

python - 查找各个序列的 R2 和斜率

python - 当 subplots=True 时,如何在 pandasplot() 方法中编辑标题大小和位置?

java - 将 JavaFX 与 Python 相结合

python - 如何叠加来自不同单元格的图?

bash - Jupyter Notebook 中的中间 bash 输出