嗨,我是数据科学的新手。从课程时代开始学习数据科学。我有熊猫数据框架如下,
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当我开始为此编写查询时,它变得越来越复杂。有什么简单的方法吗?谢谢你的帮助。
发布于 2018-10-25 13:27:11
对我来说,在重塑数据数据(交换列/索引/行等)时,使用枢轴_表格函数是相当直观的。
my_df.pivot_table(index='time', columns=my_df.index, values='value')发布于 2018-10-25 15:12:45
重现你的问题:
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')https://datascience.stackexchange.com/questions/40219
复制相似问题