如何使用数据框中的列在新数据框中创建行?

时间:2019-04-01 16:41:32

标签: python pandas dataframe

我有一个数据框,并希望使用某些列创建一个新的数据框来创建行。

这是我的数据框:

import pandas as pd
df=pd.DataFrame(columns=["TeamNumber", "C", "C1", "W", "W1", "W2","D","D1","G", "UTIL", "DATE", "TOP" ])
df=df.append({"TeamNumber": 1, "C": "PAUL", "C1": "BOB", "W": "NIC", "W1":"ED", "W2": "ROB","D": "ERIK","D1": "JOE","G": "RED", "UTIL": "JIM", "DATE": "2017-10-12", "TOP": 0}, ignore_index= True)
df=df.append({"TeamNumber": 2, "C": "PETE", "C1": "BOBBY", "W": "FRED", "W1":"TED", "W2": "ROBY","D": "DERIK","D1": "JULIAN","G": "CARL", "UTIL": "JIMMY", "DATE": "2017-10-15", "TOP": 1}, ignore_index= True)


TeamNumber   C    C1     W  W1   W2    D    D1    G  UTIL   DATE       TOP
0   1       PAUL BOB   NIC  ED  ROB  ERIK  JOE    RED  JIM  2017-10-12  0
1   2       PETE BOBBY FRED TED ROBY DERIK JULIAN CARL JIMMY 2017-10-15 1

我希望输出为:

   TOP TeamNumber  DATE Name       
0   0   1   2017-10-12  PAUL
1   0   1   2017-10-12  BOB
2   0   1   2017-10-12  NIC
3   0   1   2017-10-12  ED
4   0   1   2017-10-12  ROB
5   0   1   2017-10-12  ERIK
6   0   1   2017-10-12  JOE
7   0   1   2017-10-12  RED
8   0   1   2017-10-12  JIM
9   1   2   2017-10-15  PETE
10  1   2   2017-10-15  BOBBY
11  1   2   2017-10-15  FRED
12  1   2   2017-10-15  TED
13  1   2   2017-10-15  ROBY
14  1   2   2017-10-15  DERIK
15  1   2   2017-10-15  JULIAN
16  1   2   2017-10-15  CARL
17  1   2   2017-10-15  JIMMY    

2 个答案:

答案 0 :(得分:2)

在熊猫中检查DataFrame.melt()

df.melt(id_vars=['TOP','DATE' ,'TeamNumber'])[['TOP','DATE','TeamNumber','value']]

答案 1 :(得分:1)

df = df.set_index(['TOP','TeamNumber',"DATE"])
df = df.stack().reset_index().drop(['level_3'],axis=1).rename(columns = {0:'Name'})

输出df

    TOP TeamNumber  DATE    Name
0   0   1   2017-10-12  PAUL
1   0   1   2017-10-12  BOB
2   0   1   2017-10-12  NIC
3   0   1   2017-10-12  ED
4   0   1   2017-10-12  ROB
5   0   1   2017-10-12  ERIK
6   0   1   2017-10-12  JOE
7   0   1   2017-10-12  RED
8   0   1   2017-10-12  JIM
9   1   2   2017-10-15  PETE
10  1   2   2017-10-15  BOBBY
11  1   2   2017-10-15  FRED
12  1   2   2017-10-15  TED
13  1   2   2017-10-15  ROBY
14  1   2   2017-10-15  DERIK
15  1   2   2017-10-15  JULIAN
16  1   2   2017-10-15  CARL
17  1   2   2017-10-15  JIMMY