我正在使用Pandas数据框读取Excel文件并对此进行一些操作。我有一个包含多行的标题,现在我想按几个列值分组。但是,我无法为此找到解决方案。
Excel样本
name address contact_info
first_name last_name street city mobile email
1 AAA BBB XXX YYY 102020 [email protected]
2 111 222 333 444 239393 [email protected]
3 BBB 333 XXX dddd 102020 [email protected]
我想按街道名称分组并从我尝试过的其他列中查找值,但由于它是多索引,因此无法找到街道。
df = pd.read_excel("test.xlsx", header=[0, 1], sheet_name="Sheet1")
print df.groupby("street", level=-1)[["first_name", "last_name", "email"]].apply(list)
您将需要在各处提供元组列表:
cols = [
('name', 'first_name'),
('name', 'last_name'),
('contact_info', 'email')
]
df.groupby([('address', 'street')])[cols].apply(pd.Series.tolist)
# or, alternatively,
# df.groupby(df.address.street)[cols].apply(pd.Series.tolist)
(address, street)
333 [[111, 222, [email protected]]]
XXX [[AAA, BBB, [email protected]], [BBB, 333, [email protected]...
元组指定MultiIndex
列选择。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句