我的数据框如下:
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
现在我想创建一个分层列索引,所以我按照以下方式进行:
big_df = pd.concat([df['Student Name'], df[['Q1', 'Q2', 'Q3']]], axis=1, keys=['Name', 'IS'])
并且能够获得以下内容:
>>> 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
现在进行第二次迭代,我想只将新数据帧中的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'])
我在哪里做错误?请帮助。我是Pandas的新手
答案 0 :(得分:1)
放弃big_df
的最高级别:
big_df.columns = big_df.columns.droplevel(level=0)
连接它们,提供三个不同的帧作为输入,匹配要使用的键数:
Q_cols = ['Q1', 'Q2', 'Q3']
key_names = ['Name', 'IS', 'CC']
pd.concat([big_df[['Student Name']], big_df[Q_cols], df[Q_cols]], axis=1, keys=key_names)
答案 1 :(得分:1)
首先,您最好将索引设置为['Month', 'Roll no.', 'Student Name']
。这将简化你的concat语法,并确保你也匹配学生的名字。
df.set_index('Student Name', append=True, inplace=True)
其次,我建议您以不同的方式执行此操作并在迭代期间存储df
数据框(带有Q1 / Q2 / Q3值),并引用最高列级别的名称(例如:'IS' ,'CC')。 dict对于这个是完美的,并且pandas接受dict作为pd.concat
# Creating a dictionnary with the first df from your question
df_dict = {'IS': df}
# Iterate....
# Append the new df to the df_dict
df_dict['CC'] = df
现在,在循环之后,这是你的词典:
df_dict
In [10]: df_dict
Out[10]:
{'CC': Q1 Q2 Q3
Month Roll No Student Name
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 Kisho 8.0 5.0 3.0
4 Barretto Cleon Domnic 1.0 5.0 4.0,
'IS': Q1 Q2 Q3
Month Roll No Student Name
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 Kisho 8.0 4.0 3.0
4 Barretto Cleon Domnic 2.0 3.0 4.0}
所以现在,如果你结束,熊猫会做得很好,并自动为你服务:
In [11]: big_df = pd.concat(df_dict, axis=1)
big_df
Out[11]:
如果你真的想迭代地做,你应该在与big_df结束之前添加新的多级('CC')
df.columns = pd.MultiIndex.from_tuples([('IS', x) for x in df.columns])
# Then you can concat, give the same result as the picture above.
pd.concat([big_df, df], axis=1)