根据列表中的特定值从列表创建DataFrame

时间:2018-05-07 12:31:23

标签: python pandas

我正在帮助我的妻子为她的小学做一些工作。

我有一个看起来像这样简化的excel:

              score
NameA
test1           10
test2           23
test4           15
NameB
test1           10
test3           17
NameC
etc. 

What I would (ultimately) want is:

           Test1.   Test2.   Test3.   Test4.   etc
NameA.       10       23      Nan       Nan
NameB        10       Nan.     17.      Nan
NameC       
etc

到目前为止,我已经导入了Excel,并且所有列都已定位,想要列出给定学生的所有测试的列表,但无法使其工作。

寻找灵感,欢迎所有建议。

马腾

2 个答案:

答案 0 :(得分:1)

我建议如下:

1.以这种格式重新构建excel中的数据:

   Names   test  score
0  NameA  test1     10
1  NameA  test2     23
2  NameA  test4     15
3  NameB  test1     10
4  NameB  test3     17

2.然后,一个简单的unstack命令就会变得神奇。

df = df.set_index(['Names','test'])['score'].unstack(-1)
df.index.name = None
df.columns.name = None

print(df)
        test1  test2  test3  test4
NameA   10.0   23.0    NaN   15.0
NameB   10.0    NaN   17.0    NaN

答案 1 :(得分:0)

您可以在pandas

中更改重新格式化您的df
df=df.reset_index()
df['New']=df.A.loc[df.score=='']

df.ffill().loc[df.score!=''].pivot('New','A','score')
Out[406]: 
A     test1 test2 test3 test4
New                          
NameA    10    23  None    15
NameB    10  None    17  None