加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 11:49:51 所属栏目:Python 来源:网络整理
导读:我有一个大约100列的数据框,看起来像 Id Economics-1 English-107 English-2 History-3 Economics-zz Economics-2 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
我有一个大约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行的大型数据框,所以我正在寻找真正优化的解决方案,就像在熊猫中使用loc一样

解决方法

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

考虑以下:

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

现在

[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

做你想要的.

在您的情况下,请确保使用“ – ”字符进行拆分.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读