pandas:如何将特定列更改为索引并将索引更改为各个列

数据挖掘 Python 熊猫
2022-02-23 03:20:25

嗨,我是数据科学的新手。从课程时代学习数据科学。我的熊猫数据框如下,

   time   value

A   9      5
A   8      4
A   7      3
B   9      3
B   8      2
B   7      1
C   9      3
C   8      2
C   7      1

我想将其转换为

       A   B  C

9      5   3  3 
8      4   2  2
7      3   1  1

当我开始为此编写查询时,它变得越来越复杂。有什么简单的方法可以做到这一点?谢谢您的帮助。

2个回答

对我来说,当涉及到重塑数据框(切换列/索引/行等)时,使用pivot_table函数相当直观。

my_df.pivot_table(index='time', columns=my_df.index, values='value')

重现您的问题:

import pandas as pd
d={'time':[9, 8, 7, 9, 8, 7, 9, 8, 7],'value':[5, 4, 3, 3, 2, 1, 3, 2, 1]}
df = pd.DataFrame(data=d,index=['A', 'A', 'A', 'B','B','B','C','C','C'])

使用带有 for 循环的函数。

def change_my_df(give_df,column_to_index,value_in_cell):
"""Specify the dataframe, the column that will become the new inex, the column that will populate the cell of the new df"""
    new_index=give_df[column_to_index].unique().tolist()
    new_columns=list(set(give_df.index.values))
    new_df=pd.DataFrame(index=new_index,columns=new_columns)
    for l,r in give_df.iterrows():
        new_df[l][r[str(column_to_index)]]=r[str(value_in_cell)]
    return new_df
new_df=change_my_df(df,'time','value')