按所有列拆分数据框并插入到数据框列表中

split data frame by all columns and insert in to a list of data frames

有没有办法在每列的数据帧列表中拆分一个数据帧,然后在列名中添加一个计数器或其他东西,例如ab_a、cd_a

示例的一些随机数据

data = pd.DataFrame({'ab': [1, 3, 1, 4, -1, 1],
                     'cd': [1, 1, -0, 1, -0],
                     'ef': [1, 2, 1, 1, 2],
                     'gh': [1, 4, 2, 3, 1]})

预期的输出类似于

lst = [ab \ 
1
2
1
4 
-1 
1,

cd \
1
1
-0
1
-0,

ef\
1 
2
1
1
2,

gh\
1
4
2
3
1]

您可以在其中访问列表中的每个元素,例如lst[0] - 将 ab 列输出为单个数据框

**ab**
1
2
1
4
-1
1

谢谢!

您可以使用 .pop 然后 .to_frame()。例如:

lst = [data.pop(col).to_frame() for col in data.columns]
print(lst)

打印:

[   ab
0   1
1   3
2   1
3   4
4  -1,    cd
0   1
1   1
2   0
3   1
4   0,    ef
0   1
1   2
2   1
3   1
4   2,    gh
0   1
1   4
2   2
3   3
4   1]

那么你可以这样做:

# print first dataframe
print(lst[0])

打印:

   ab
0   1
1   3
2   1
3   4
4  -1

你可以使用to_dict(orient='list') -

result = list(df.to_dict(orient='list').values())

输出-

print(result[1])
[1, 1, 0, 1, 0]