[英]Split a multi-index dataframe in dataframes by column names
我有一個如下所示的數據框:按列的多索引數據框
我想獲得 3 個數據幀,命名為每列(指南針、加速、陀螺儀),時間索引未受影響,每列三列(df1、df2、df3)。
我已經嘗試for index,row in df.iterrows():
但無法真正讓它工作而且我在想stack()
和 unstack unstack()
但真的不知道如何。
您可以將前 3 列保存在 csv 文件中,然后對其他 csv 文件重復該過程 2 次...
您可以像這樣選擇數據框的 3 列:
x = 0
data=pd.read_csv(file.csv, keep_default_na=False, skiprows=line_header, na_filter=False, usecols=[x,x+1,x+2])[[compass, accel, gyro]])
其中 x = “大數據框”的第一列
在這種情況下 usecols 屬性非常有用
您可以在以下位置閱讀更多信息: Pandas.read_csv
groupby
允許您沿具有相同 level_values 的 MultiIndex 級別拆分 DataFrame。 我們將使用DataFrame.xs
刪除分組索引級別,只留下您關心的列。 單獨的 DataFrame 存儲在字典中,由原始列 MultiIndex 的唯一級別 1 值鍵控。
import pandas as pd
import numpy as np
np.random.seed(123)
df = pd.DataFrame(np.random.randint(1, 10, (4, 9)),
columns=pd.MultiIndex.from_product([['df1', 'df2', 'df3'],
['compass', 'gyro', 'accel']]))
# df1 df2 df3
# compass gyro accel compass gyro accel compass gyro accel
#0 3 3 7 2 4 7 2 1 2
#1 1 1 4 5 1 1 5 2 8
#2 4 3 5 8 3 5 9 1 8
#3 4 5 7 2 6 7 3 2 9
d = {idx: gp.xs(idx, level=1, axis=1) for idx,gp in df.groupby(level=1, axis=1)}
d['gyro']
# df1 df2 df3
#0 3 4 1
#1 1 1 2
#2 3 3 1
#3 5 6 2
由於這樣的拆分可以通過groupby
輕松獲得,您甚至可能不需要存儲單獨的 DataFrame; 您可以使用GroupBy.apply
分別操作它們中的每一個。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.