我正在使用XLS格式的这种数据形式:
+--------+---------+-------------+---------------+---------+
| ID | Branch | Customer ID | Customer Name | Balance |
+--------+---------+-------------+---------------+---------+
| 111111 | Branch1 | 1 | Company A | 10 |
+--------+---------+-------------+---------------+---------+
| 222222 | Branch2 | 2 | Company B | 20 |
+--------+---------+-------------+---------------+---------+
| 111111 | Branch1 | 2 | Company B | 30 |
+--------+---------+-------------+---------------+---------+
| 222222 | Branch2 | 3 | Company C | 10 |
+--------+---------+-------------+---------------+---------+
我想用Pandas来处理它。熊猫会把它读成单张,但我想在这里使用MultiIndex,比如
+--------+---------+-------------+---------------+---------+
| ID | Branch | Customer ID | Customer Name | Balance |
+--------+---------+-------------+---------------+---------+
| | | 1 | Company A | 10 |
+ 111111 + Branch1 +-------------+---------------+---------+
| | | 2 | Company B | 30 |
+--------+---------+-------------+---------------+---------+
| | | 2 | Company B | 20 |
+ 222222 + Branch2 +-------------+---------------+---------+
| | | 3 | Company C | 10 |
+--------+---------+-------------+---------------+---------+
此处111111
和Branch1
是1级索引,1
Company A
是2级索引。有内置的方法吗?
答案 0 :(得分:1)
如果只需要set_index
和sort_index
,请使用:
df.set_index(['ID','Branch', 'Customer ID','Customer Name'], inplace=True)
df.sort_index(inplace=True)
print (df)
Balance
ID Branch Customer ID Customer Name
111111 Branch1 1 Company A 10
2 Company B 30
222222 Branch2 2 Company B 20
3 Company C 10
但如果MultiIndex
(我的解决方案中a
,b
只需要两个级别,则必须先连接第二列,第三列连接第四列:
df['a'] = df.ID.astype(str) + '_' + df.Branch
df['b'] = df['Customer ID'].astype(str) + '_' + df['Customer Name']
#delete original columns
df.drop(['ID','Branch', 'Customer ID','Customer Name'], axis=1, inplace=True)
df.set_index(['a','b'], inplace=True)
df.sort_index(inplace=True)
print (df)
Balance
a b
111111_Branch1 1_Company A 10
2_Company B 30
222222_Branch2 2_Company B 20
3_Company C 10
如果需要按前一列汇总最后一列,请将groupby
与GroupBy.mean
一起使用:
df = df.groupby(['ID','Branch', 'Customer ID','Customer Name'])['Balance'].mean().to_frame()
print (df)
Balance
ID Branch Customer ID Customer Name
111111 Branch1 1 Company A 10
2 Company B 30
222222 Branch2 2 Company B 20
3 Company C 10
如果在set_index
中使用MultiIndex
列需要tuples
:
df.columns = pd.MultiIndex.from_arrays([['a'] * 2 + ['b']* 2 + ['c'], df.columns])
print (df)
a b c
ID Branch Customer ID Customer Name Balance
0 111111 Branch1 1 Company A 10
1 222222 Branch2 2 Company B 20
2 111111 Branch1 2 Company B 30
3 222222 Branch2 3 Company C 10
df.set_index([('a','ID'), ('a','Branch'),
('b','Customer ID'), ('b','Customer Name')], inplace=True)
df.sort_index(inplace=True)
print (df)
c
Balance
(a, ID) (a, Branch) (b, Customer ID) (b, Customer Name)
111111 Branch1 1 Company A 10
2 Company B 30
222222 Branch2 2 Company B 20
3 Company C 10