将多个数据帧合并为一个数据帧,每个数据帧作为包含多列的标题名称,并创建一个3D数据帧



我有多个数据帧df1、df2、df3等到df10。数据帧有135列。每个看起来都是这样的:

b>cde<1th>f<2th>g478
时间 a
1 2 356

您可以在Pandasconcat命令中使用keys(使用带f-string的正确range创建相关命名法或使用已定义的list1(:

序列,默认无

如果通过了多个级别,则应包含元组。使用传递的键作为最外层来构造层次索引。

import pandas as pd
import numpy as np
# setup
np.random.seed(12345)
all_df_list = []
for i in range(3):
d = {
'time': (pd.timedelta_range(start='00:01:00', periods=5, freq='1s')
+ pd.Timestamp("00:00:00")).strftime("%M:%S"),
'a': np.random.rand(5),
'b': np.random.rand(5),
'c': np.random.rand(5),
}
all_df_list.append(pd.DataFrame(d).round(2))
# code
dfc = pd.concat(all_df_list, axis=1,
keys=[f'df{i}' for i in range(1,4)]) # use the correct 'range' or your already defined 'list1'
dfc = dfc.set_index(dfc.df1.time)
dfc = dfc.drop('time', axis=1, level=1)
print(dfc)
df1               df2               df3
a     b     c     a     b     c     a     b     c
time
01:00  0.93  0.60  0.75  0.66  0.64  0.73  0.03  0.53  0.82
01:01  0.32  0.96  0.96  0.81  0.72  0.99  0.80  0.60  0.50
01:02  0.18  0.65  0.01  0.87  0.47  0.68  0.90  0.05  0.81
01:03  0.20  0.75  0.11  0.96  0.33  0.79  0.02  0.90  0.10
01:04  0.57  0.65  0.30  0.72  0.44  0.17  0.49  0.73  0.22

df2中提取ab

In [190]: dfc.df2[['a','b']]
Out[190]:
a     b
time
01:00  0.66  0.64
01:01  0.81  0.72
01:02  0.87  0.47
01:03  0.96  0.33
01:04  0.72  0.44

最新更新