我的数据框是一组数据记录,每个数据记录长度为400个通道,每个通道编号列在我的数据帧的通道列下,如下所示,
index channel input Baseline
0 0 2129 2129
1 1 2128 2129
2 2 2129 2129
3 3 2129 2129
4 4 2129 2129
5 5 2129 2129
...
396 396 2128 2127
397 397 2128 2127
398 398 2127 2127
399 399 2127 2127
400 0 2130 2128
401 1 2130 2128
402 2 2131 2128
...
等等
我要做的是设置索引,以便每个系列的400个频道分别被编入索引,
index channel input Baseline
0 0 2129 2129
1 2128 2129
2 2129 2129
3 2129 2129
4 2129 2129
5 2129 2129
...
396 2128 2127
397 2128 2127
398 2127 2127
399 2127 2127
1 0 2130 2128
1 2130 2128
2 2131 2128
...
道歉,如果这是一个非常明显的事情,但我在使用python和一般代码方面有点初学者
编辑:感谢您的帮助!令人惊讶的是python3中的groupby函数被错误地
答案 0 :(得分:0)
df = df.set_index(df.groupby('channel').cumcount())
print (df)
channel input Baseline
0 0 2129 2129
0 1 2128 2129
0 2 2129 2129
0 3 2129 2129
0 4 2129 2129
0 5 2129 2129
0 396 2128 2127
0 397 2128 2127
0 398 2127 2127
0 399 2127 2127
1 0 2130 2128
1 1 2130 2128
1 2 2131 2128
或者如果需要MultiIndex
:
df = df.set_index([df.groupby('channel').cumcount(), 'channel'])
print (df)
input Baseline
channel
0 0 2129 2129
1 2128 2129
2 2129 2129
3 2129 2129
4 2129 2129
5 2129 2129
396 2128 2127
397 2128 2127
398 2127 2127
399 2127 2127
1 0 2130 2128
1 2130 2128
2 2131 2128
首先创建新列:
df['idx'] = df.groupby('channel').cumcount()
df = df.set_index(['idx', 'channel'])
print (df)
input Baseline
idx channel
0 0 2129 2129
1 2128 2129
2 2129 2129
3 2129 2129
4 2129 2129
5 2129 2129
396 2128 2127
397 2128 2127
398 2127 2127
399 2127 2127
1 0 2130 2128
1 2130 2128
2 2131 2128