【问题标题】:How to split a dataframe to multiple dataframes bases on column names如何根据列名将数据框拆分为多个数据框
【发布时间】:2026-01-18 21:25:02
【问题描述】:

我的数据框如下,

 _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__all/any/none 可以存在)或其他值开头。我希望所有以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.) 有没有更简单的方法可以将键和数据框作为值拆分成字典?

请帮忙。

【问题讨论】:

  • 您是否尝试过使用 loc 明确命名要存储到新数据框中的列?
  • 我无法重命名列,因为数据框是网络爬虫的输出。
  • 不,我的意思是new_df = df[['3ME__ Q219', '3ME__ Q218' .... '3ME__ Q21n']]
  • 如果列名不同,并且您只想检查“3ME”之类的“关键字”,请将您的 df 列名存储到列表中并按条目进行拆分,然后将哪个存储到新列表中名称返回真或假,然后使用这些列表使用它们在df.colums中的索引来引用您的df@
  • @Joe,就像 webscraper 的输出一样,我不知道数据帧头会是什么。 dtataframe 可能包含也可能不包含以3ME__,`6ME__'..etc 开头的列标题

标签: python python-3.x pandas dataframe dictionary


【解决方案1】:

我会做以下事情:

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

【讨论】:

  • 我已经尝试过这种方法,但它会为others 创建单独的数据帧,即在这种情况下为Q418Q219 创建单独的df。我希望所有其他人都在一个数据框中。
  • @Shijith 将所有此类列设置为索引,然后尝试此方法。你有多少这样的专栏?
  • 这里我不确定数据框将包含什么,我期待一个带有 t_headr_head 和一些值的数据框(不知道哪些值 - 可能不同)
  • @Shijith 那么您打算根据什么将它们组合在一起?如我所见,任何列都可以有一个_
  • 最后两列没有'__',如果len(df.columns.str.split('__')) == 2 上的m.columns.str.split('_').str[0]', for the rest of column headings with lenth ==1` 应该全部分组到一个数据帧,我想拆分成不同的数据帧
【解决方案2】:

您可以检索您创建的数据框的列名并按不在其中的列进行选择:

other_columns = [x for x in df.columns if x not in (list(df1.columns) + list(df2.columns) + list(df3.columns))]

other_df = df[other_columns]

【讨论】:

    【解决方案3】:

    你也可以这样试试:

    k = list(df1.columns)+ list(df2.columns)+ list(df3.columns)
    
    df = df.drop(k, axis=1)
    print(df)
    

    【讨论】:

      【解决方案4】:

      以上所有因素的结合让我找到了我正在寻找的东西,

      def _split_dataframes(df):
          df = df.set_index(['t_head','r_head'])
          final_dict_key = 0
          final_dict = {}
          names_list = []
          for elems in ['3ME__','6ME__','9ME__','other']:
              if elems != 'other':
                  temp_df = df.filter(regex=elems)
                  temp_df = temp_df.loc[(temp_df!='').all(axis=1)]
                  names_list.extend(list(temp_df.columns))
                  if not temp_df.empty:
                      temp_df.reset_index(inplace=True)
                      final_dict[str(final_dict_key)] = temp_df
                      final_dict_key+= 1
      
              else:
                  df.drop(names_list, axis=1,inplace=True)
                  df = df.loc[(df!='').all(axis=1)]
                  if not df.empty:
                      df.reset_index(inplace=True)
                      final_dict[str(final_dict_key)] = df
      

      这将拆分主数据框并保存到带有增量键的字典,如下所示

      {
       '0':
           t_head   r_head 3ME__ Q219 3ME__ Q218 3ME__ Q119 3ME__ Q18 3ME__ Q418
         0     H1  Revenue      159.9      112.3        121      85.7      160.5
         1     H3   Income       45.6       27.2       23.1      15.3       51.1, 
       '1': 
           t_head   r_head 6ME__ Q219 6ME__ Q218
         0     H2  Revenue      280.9        198
         1     H4   Income       68.7       42.6, 
       '2':
            t_head   r_head 9ME__ Q417 9ME__ Q318 9ME__ Q317
         0     H1  Revenue      102.6      118.8       79.4
         1     H3   Income       24.2       30.2       15.3, 
       '3':
            t_head    r_head  Q219  Q418
         0     H5      Cash  1305  2072
         1     H6  Expenses  1239  1117
      }
      

      【讨论】: