数据框python将水平和垂直方向上的某些值重塑

时间:2019-03-01 08:56:21

标签: python dataframe

我有92列和13行数据框,其中每一行对应一个扑克手。列(并非全部)的名称和值如下所示:

'Soft','Hand_ID','Table_Size', 'Blinds', 'Day', 'No_of_players', 'Seat_1','Seat_2','Seat_3', 'Seat_4', 'Seat_5', 'Seat_6'
PokerStars  172109655423    6-max   €0.50/€1.00 2017/06/22  4   KO  fasolakia14 Johnii141   bogec   0   0
PokerStars  143736274858    6-max   £0.25/£0.50 2015/11/13  6   Racushniak  koluha1000  Bantina DMIGNN  Johnii141   vor4mohs

我需要将以下列调整为垂直:“ Seat_1”,“ Seat_2”,“ Seat_3”,“ Seat_4”,“ Seat_5”,“ Seat_6”。 输出应如下所示: Output

2 个答案:

答案 0 :(得分:0)

只需使用pd.melt。整个DataFrame中没有看到很多列是因为。 代码如下所示:     df_Seats = pd.melt(df,id_vars = ['Hand_ID','Soft','Table_Size','Blinds','Day','No_of_players','Pot','Rake'],                     value_vars = ['Seat_1','Seat_2','Seat_3','Seat_4','Seat_5','Seat_6'],                     var_name ='Seats_var',value_name ='Seats')

df_Seats = df_Seats.drop('Seats_var', 1)

输出外观: http://prntscr.com/mrzu3z 但仍然不知道如何解决Hand_Id,Soft等值重复的问题。

答案 1 :(得分:0)

假设您有pandas.DataFrame,我真的不希望使用pd.melt。我建议使用这样的简单解决方案。

>>> df
Soft    Hand_ID Table_Size  Blinds  Day No_of_players   Seat_1  Seat_2  Seat_3  Seat_4  Seat_5  Seat_6
PokerStars  172109655423    6-max   €0.50/€1.00 2017/06/22  4   KO  fasolakia14 Johnii141   bogec   0   0
PokerStars  143736274858    6-max   £0.25/£0.50 2015/11/13  6   Racushniak  koluha1000  Bantina DMIGNN  Johnii141   vor4mohs

只需将您的座位列添加到一列中

>>> df['Seats'] = df['Seat_1'] + " " + df['Seat_2'] + " " + df['Seat_3'] + " " + df['Seat_4'] + " " + df['Seat_5'] + " " + df['Seat_6']
>>> df.drop(['Seat_1', 'Seat_2', 'Seat_3', 'Seat_4', 'Seat_5', 'Seat_6'], axis=1)

您将获得所需的输出

Soft    Hand_ID Table_Size  Blinds  Day No_of_players   Seats
PokerStars  172109655423    6-max   €0.50/€1.00 2017/06/22  4   KO fasolakia14 Johnii141 bogec 0 0
PokerStars  143736274858    6-max   £0.25/£0.50 2015/11/13  6   Racushniak koluha1000 Bantina DMIGNN Johnii141...