我的数据框如下,
_dict = {'t_head': ['H1', 'H2', 'H3', 'H4', 'H5','H6'],
'r_head': ['Revenue', 'Revenue', 'Income', 'Income', 'Cash', 'Expenses'],
'3ME__ Q219': [159.9, '', 45.6, '', '', ''],
'3ME__ Q218': [112.3, '', 27.2, '', '', ''],
'3ME__ Q119': [121.0, '', 23.1, '', '', ''],
'3ME__ Q18': [85.7, '', 15.3, '', '', ''],
'3ME__ Q418': [160.5, '', 51.1, '', '', ''],
'9ME__ Q417': [102.6, '', 24.2, '', '', ''],
'9ME__ Q318': [118.8, '', 30.2, '', '', ''],
'9ME__ Q317': [79.4, '', 15.3, '', '', ''],
'6ME__ Q219': ['', 280.9, '', 68.7, '', ''],
'6ME__ Q218': ['', 198.0, '', 42.6, '', ''],
'Q219': ['', '', '', '', 1305, 1239],
'Q418': ['', '', '', '', 2072, 1117]
}
df = pd.DataFrame.from_dict(_dict)
print(df)
t_head r_head 3ME__ Q219 3ME__ Q218 3ME__ Q119 3ME__ Q18 3ME__ Q418 9ME__ Q417 9ME__ Q318 9ME__ Q317 6ME__ Q219 6ME__ Q218 Q219 Q418
0 H1 Revenue 159.9 112.3 121 85.7 160.5 102.6 118.8 79.4
1 H2 Revenue 280.9 198
2 H3 Income 45.6 27.2 23.1 15.3 51.1 24.2 30.2 15.3
3 H4 Income 68.7 42.6
4 H5 Cash 1305 2072
5 H6 Expenses 1239 1117
我想根据列标题将此数据框拆分为多个数据框。这里的列标题可以以 3ME__
、6ME__
、9ME__
开头(所有/任何/无都可以是present) 或其他值。我希望所有以 3ME__
开头的列都在一个数据框中,6ME__
到另一个......等等。其余的都在第四个数据框中。
我试过的是如下,
df1 = df.filter(regex='3ME__')
if not df1.empty:
df1 = df1[df1.iloc[:,0].astype(bool)]
df2 = df.filter(regex='6ME__')
if not df2.empty:
df2 = df2[df2.iloc[:,0].astype(bool)]
df3 = df.filter(regex='9ME__')
if not df3.empty:
df3 = df3[df3.iloc[:,0].astype(bool)]
在这里,我能够过滤掉以3ME__
、6ME__
& 9ME__
开头的列名称到不同的数据帧,但不能将其余列标题放入一个数据框。
1.) 如何将其余列标题添加到一个数据框中?
2.) 有没有更简单的方法以键和数据帧作为值拆分成字典?
请帮助。
最佳答案
我会做以下事情:
m=df.set_index(['t_head','r_head']) #set the 2 columns as index
然后在轴 1 上拆分列和分组,并对每个组进行字典
d={f'df_{i}': g for i, g in m.groupby(m.columns.str.split('_').str[0],axis=1)}
然后调用每个键来访问这个字典:
print(d['df_3ME'])
根据进一步的讨论,我们进行相同的操作,但有一个条件:
cond=df.columns.str.contains('__') #check if cols have double _
d={f'df_{i}':g for i, g in
df.loc[:,cond].groupby(df.loc[:,cond].columns.str.split('__').str[0],axis=1)}
d.update({'Misc':df.loc[:,~cond]}) #update the dict with all that doesnt meet condition
print(d['df_3ME'])
3ME__ Q219 3ME__ Q218 3ME__ Q119 3ME__ Q18 3ME__ Q418
0 159.9 112.3 121 85.7 160.5
1
2 45.6 27.2 23.1 15.3 51.1
3
4
5
print(d['Misc'])
t_head r_head Q219 Q418
0 H1 Revenue
1 H2 Revenue
2 H3 Income
3 H4 Income
4 H5 Cash 1305 2072
5 H6 Expenses 1239 1117
关于python - 如何根据列名将数据框拆分为多个数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57802524/