重现您的问题:
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')