我有一个数据帧如下:
df.head()
Student Name Q1 Q2 Q3
Month Roll No
2016-08-01 0 Save Mithil Vinay 0.0 0.0 0.0
1 Abraham Ancy Chandy 6.0 5.0 5.0
2 Barabde Pranjal Sanjiv 7.0 5.0 5.0
3 Bari Siddhesh Kishor 8.0 5.0 3.0
4 Barretto Cleon Domnic 1.0 5.0 4.0
现在我想创建一个层次化的列索引,所以我按如下方式进行:
^{pr2}$并且能够得到以下信息:
>>> big_df
Name IS
Student Name Q1 Q2 Q3
Month Roll No
2016-08-01 0 Save Mithil Vinay 0.0 0.0 0.0
1 Abraham Ancy Chandy 6.0 5.0 5.0
2 Barabde Pranjal Sanjiv 7.0 5.0 5.0
3 Bari Siddhesh Kishor 8.0 5.0 3.0
4 Barretto Cleon Domnic 1.0 5.0 4.0
现在对于第二次迭代,我只想将新dataframe中的Q1, Q2, Q3
值连接到big_df
数据帧(之前连接的数据帧)。现在第二次迭代的数据帧如下:
Student Name Q1 Q2 Q3
Month Roll No
2016-08-01 0 Save Mithil Vinay 0.0 0.0 0.0
1 Abraham Ancy Chandy 8.0 5.0 5.0
2 Barabde Pranjal Sanjiv 7.0 5.0 4.0
3 Bari Siddhesh Kishor 8.0 4.0 3.0
4 Barretto Cleon Domnic 2.0 3.0 4.0
我想要big_df
如下:
Name IS CC
Student Name Q1 Q2 Q3 Q1 Q2 Q3
Month Roll No
2016-08-01 0 Save Mithil Vinay 0.0 0.0 0.0 0.0 0.0 0.0
1 Abraham Ancy Chandy 6.0 5.0 5.0 8.0 5.0 5.0
2 Barabde Pranjal Sanjiv 7.0 5.0 5.0 7.0 5.0 4.0
3 Bari Siddhesh Kishor 8.0 5.0 3.0 8.0 4.0 3.0
4 Barretto Cleon Domnic 1.0 5.0 4.0 2.0 3.0 4.0
我尝试了以下代码,但都出错了:
big_df.concat([df[['Q1', 'Q2', 'Q3']]], axis=1, keys=['CC'])
pd.concat([big_df, df[['Q1', 'Q2', 'Q3']]], axis=1, keys=['Name', 'CC'])
我在哪里犯错误?请帮忙。我对熊猫不熟悉
删除
big_df
的最高层:将它们串联起来,提供三个不同的帧作为输入,以匹配要使用的键数:
^{pr2}$首先,最好将索引设置为
['Month', 'Roll no.', 'Student Name']
。这将大大简化您的concat语法,并确保您与学生的名字匹配。在其次,我建议您以不同的方式来执行此操作,并在迭代期间存储
^{pr2}$df
数据帧(Q1/Q2/Q3值),同时引用最高列级别的名称(例如:“IS”、“CC”)。dict将非常适合于此,pandas确实接受dict作为pd.concat
的参数现在,在循环之后,你的结论是:
所以现在如果你吃海螺,熊猫会做得很好,而且会自动为你:
如果您真的想迭代地完成它,您应该在使用big_df进行concat之前预先准备好新的多级(“CC”)
相关问题 更多 >
编程相关推荐