''Series'对象是可变的,因此在尝试对列求和并且数据类型为float时不能对其进行哈希处理

问题描述 投票:0回答:1

我正在尝试使用以下几列来汇总从几千列的第三列到最后一列的所有值:

day3prep['D3counts'] = day3prep.sum(day3prep.iloc[:, 2:].sum(axis=1))

数据帧的格式为:

ID G1  Z1  Z2 ...ZN
0  50  13  12 ...62
1  51  62  23 ...19

dataframe with summed column:
ID G1  Z1  Z2 ...ZN D3counts
0  50  13  12 ...62 sum(Z1:ZN in row 0)
1  51  62  23 ...19 sum(Z1:ZN in row 1)

我将NaN更改为0。数据类型是浮点型,但我得到了错误:

'Series' objects are mutable, thus they cannot be hashed
pandas sum mutable
1个回答
0
投票

您只需要此部分:

day3prep['D3counts'] = day3prep.iloc[:, 2:].sum(axis=1)

带有一些随机数:

import pandas as pd
import random

random.seed(42)
day3prep = pd.DataFrame({'ID': random.sample(range(10), 5), 'G1': random.sample(range(10), 5),
    'Z1': random.sample(range(10), 5), 'Z2': random.sample(range(10), 5), 'Z3': random.sample(range(10), 5)})

day3prep['D3counts'] = day3prep.iloc[:, 2:].sum(axis=1)

输出:

> day3prep


    ID  G1  Z1  Z2  Z3  D3counts
0   1   2   0   8   8        16
1   0   1   9   0   6        15
2   4   8   1   3   3         7
3   9   4   7   5   7        19
4   6   3   6   6   4        16
© www.soinside.com 2019 - 2024. All rights reserved.