如果我明白你在找什么…
从这个数据框架开始,我相信这就是你所拥有的:
ID 1 2 3
0 Date Review Average Review
1 01/01/18 2 4 3
2 02/01/18 1 2 4
假设你做你的
pd.melt()
然后剩下的是:
new_df = pd.melt(df,id_vars=['ID'],var_name=['Store'],value_name='Score').fillna(0).set_index('ID')
Store Score
ID
Date 1 Review
01/01/18 1 2
02/01/18 1 1
Date 2 Average
01/01/18 2 4
02/01/18 2 2
Date 3 Review
01/01/18 3 3
02/01/18 3 4
然后你可以做如下的事情:
# sort index so all the 'Date' values are at the bottom
new_df.sort_index(inplace=True)
# create a new df of just the dates becuase that is your review types
review_types = new_df.loc['Date']
# rename column to review types
review_types.rename(columns={'Score':'Review Type'}, inplace=True)
# remove new_df.loc['Date']
# new_df = new_df.drop(new_df.tail(len(review_types)).index).reset_index()
# UPDATED removal of new_df.loc['Date']
# I recommend removing the date values by doing this and not using .tail()
new_df = new_df[~new_df.index.str.contains('Date')].reset_index()
# rename ID column to Date
new_df.rename(columns={'ID':'Date'}, inplace=True)
# merge your two dataframes together
new_df.merge(review_types, on='Store')
这给了你:
Date Store Score Review Type
0 01/01/18 1 2 Review
1 02/01/18 1 1 Review
2 01/01/18 2 4 Average
3 02/01/18 2 2 Average
4 01/01/18 3 3 Review
5 02/01/18 3 4 Review