在pandas dataframe中以相同字符串开头的列的值的总和

时间:2016-03-02 12:09:34

标签: python pandas dataframe startswith

我有一个大约有100列的数据框,看起来像

   Id  Economics-1  English-107  English-2  History-3  Economics-zz  Economics-2  \
0  56          1            1          0        1       0           0   
1  11          0            0          0        0       1           0   
2   6          0            0          1        0       0           1   
3  43          0            0          0        1       0           1   
4  14          0            1          0        0       1           0   

   Histo      Economics-51      Literature-re         Literatureu4  
0           1            0           1                0  
1           0            0           0                1  
2           0            0           0                0  
3           0            1           1                0  
4           1            0           0                0  

所以我的目标是只留下更多的全球类别:只有英语,历史,文学,并在这些数据帧中写下它的价值总和。组件,例如英语:英语-107,英语-2

    Id  Economics      English    History  Literature  
0  56          1            1          2        1                     
1  11          1            0          0        1                    
2   6          0            1          1        0                     
3  43          2            0          1        1                     
4  14          0            1          1        0          

所以对于那些提议我真的这两个方法

      first method:

df=pd.read_csv(file_path, sep='\t')
df['History']=df.loc[df[df.columns[pd.Series(df.columns).str.startswith('History')]].sum(axes=1)]

第二种方法:

    df=pd.read_csv(file_path, sep='\t')
    filter_col = [col for col in list(df) if col.startswith('History')]
    df['History']=0 #initialize value, otherwise throws KeyError
    for c in df[filter_col]:
    df['History']=df[filter_col].sum(axes=1)
    print df['History', df[filter_col]]

,但都给我错误

  

TypeError: 'DataFrame' objects are mutable, thus they cannot be hashed

您能否建议我如何调试此错误,或者为我的问题解决另一个问题。请注意,我有一个包含大约100列和400000行的大型数据框,所以我正在寻找真正优化的解决方案,就像在pandas中使用loc一样

3 个答案:

答案 0 :(得分:7)

我建议您做一些不同的事情,即执行转置,按行的前缀(原始列),总和和转置进行分组。

请考虑以下事项:

df = pd.DataFrame({
        'a_a': [1, 2, 3, 4],
        'a_b': [2, 3, 4, 5],
        'b_a': [1, 2, 3, 4],
        'b_b': [2, 3, 4, 5],
    })

现在

[s.split('_')[0] for s in df.T.index.values]

是列的前缀。所以

>>> df.T.groupby([s.split('_')[0] for s in df.T.index.values]).sum().T
    a   b
0   3   3
1   5   5
2   7   7
3   9   9

做你想做的事。

在您的情况下,请务必使用'-'字符进行拆分。

答案 1 :(得分:2)

使用出色的DSM理念:

from __future__ import print_function

import pandas as pd

categories = set(['Economics', 'English', 'Histo', 'Literature'])

def correct_categories(cols):
    return [cat for col in cols for cat in categories if col.startswith(cat)]    

df = pd.read_csv('data.csv', sep=r'\s+', index_col='Id')

#print(df)
print(df.groupby(correct_categories(df.columns),axis=1).sum())

输出:

    Economics  English  Histo  Literature
Id
56          1        1      2           1
11          1        0      0           1
6           1        1      0           0
43          2        0      1           1
14          1        1      1           0

这是另一个版本,它负责" Histo / History"问题..

from __future__ import print_function

import pandas as pd

#categories = set(['Economics', 'English', 'Histo', 'Literature'])

#
# mapping: common starting pattern: desired name
#
categories = {
    'Histo': 'History',
    'Economics': 'Economics',
    'English': 'English',
    'Literature': 'Literature'
}

def correct_categories(cols):
    return [categories[cat] for col in cols for cat in categories.keys() if col.startswith(cat)]

df = pd.read_csv('data.csv', sep=r'\s+', index_col='Id')
#print(df.columns, len(df.columns))
#print(correct_categories(df.columns), len(correct_categories(df.columns)))
#print(df.groupby(pd.Index(correct_categories(df.columns)),axis=1).sum())

rslt = df.groupby(correct_categories(df.columns),axis=1).sum()
print(rslt)
print('History\n', rslt['History'])

输出:

    Economics  English  History  Literature
Id
56          1        1        2           1
11          1        0        0           1
6           1        1        0           0
43          2        0        1           1
14          1        1        1           0
History
 Id
56    2
11    0
6     0
43    1
14    1
Name: History, dtype: int64

PS您可能想要将缺失的类别添加到categories地图/字典

答案 2 :(得分:2)

您可以使用这些来创建以特定名称开头的列的总和,

df['Economics']= df[list(df.filter(regex='Economics'))].sum(axis=1)