gpt4 book ai didi

python - 对 pandas 数据框中包含字符串的列进行求和

转载 作者:行者123 更新时间:2023-12-01 07:50:04 25 4
gpt4 key购买 nike

我正在尝试做一些相对简单的事情,对 pandas 数据框中包含特定字符串的所有列进行求和。然后根据总和将其作为数据框中的新列。这些列都是数字浮点值...

我可以获得包含我想要的字符串的列列表

StmCol = [col for cdf.columns if 'Stm_Rate' in col]

但是当我尝试使用以下方法对它们求和时:cdf['PadStm'] = cdf[StmCol].sum()

我得到一个充满“nan”值的新列。

最佳答案

您需要传入axis=1 to .sum ,默认情况下(axis=0)对每列求和:

In [11]: df = pd.DataFrame([[1, 2], [3, 4]], columns=["A", "B"])

In [12]: df
Out[12]:
A B
0 1 2
1 3 4

In [13]: df[["A"]].sum() # Here I'm passing the list of columns ["A"]
Out[13]:
A 4
dtype: int64

In [14]: df[["A"]].sum(axis=1)
Out[14]:
0 1
1 3
dtype: int64

只有后者才匹配df的索引:

In [15]: df["C"] = df[["A"]].sum()

In [16]: df["D"] = df[["A"]].sum(axis=1)

In [17]: df
Out[17]:
A B C D
0 1 2 NaN 1
1 3 4 NaN 3

关于python - 对 pandas 数据框中包含字符串的列进行求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56280580/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com