Python Pandas:如何使用 if 条件按行求和?
Python Pandas: How do I sumproduct by rows with an if condition?
我知道 Sumproduct 上有一些关于 Stack Overflow 的问题,但解决方案对我不起作用。我也是新手 Python Pandas.
对于每一行,仅当列 ['2020'] !=0 时,我才想对某些列进行求和。
我使用了以下代码,但出现错误:
索引错误: ('index 2018 is out of bounds for axis 0 with size 27', 'occurred at index 0')
请帮忙。谢谢
# df_copy is my dataframe
column_list=[2018,2019]
weights=[6,9]
def test(df_copy):
if df_copy[2020]!=0:
W_Avg=sum(df_copy[column_list]*weights)
else:
W_Avg=0
return W_Avg
df_copy['sumpr']=df_copy.apply(test, axis=1)
df_copy
**|2020 | 2018 | 2019 | sumpr|**
|0 | 100 | 20 | 0 |
|1 | 30 | 10 | 270 |
|3 | 10 | 10 | 150 |
如果 table 看起来不像 table,我很抱歉。我无法在 Whosebug 中正确创建 table。
基本上对于特定行,如果
2020 = 2 ,
2018 =30 ,
2019 =10 ,
sumpr= 30 * 9 + 10*9 = 270
您的列名很可能是 字符串,而不是整数。
为了确认,运行 df_copy.columns
你应该会收到类似这样的信息:
Index(['2020', '2018', '2019'], dtype='object')
(注意列名周围的撇号)。
因此将您的列列表更改为:
column_list = ['2018', '2019']
在您的函数中,还将列名称更改为字符串:
df_copy['2020']
那么你的代码应该 运行.
你也可以运行更简洁的代码:
df_copy['sumpr'] = np.where(df_copy['2020'] != 0, (df_copy[column_list]
* weights).sum(axis=1), 0)
我知道 Sumproduct 上有一些关于 Stack Overflow 的问题,但解决方案对我不起作用。我也是新手 Python Pandas.
对于每一行,仅当列 ['2020'] !=0 时,我才想对某些列进行求和。 我使用了以下代码,但出现错误:
索引错误: ('index 2018 is out of bounds for axis 0 with size 27', 'occurred at index 0')
请帮忙。谢谢
# df_copy is my dataframe
column_list=[2018,2019]
weights=[6,9]
def test(df_copy):
if df_copy[2020]!=0:
W_Avg=sum(df_copy[column_list]*weights)
else:
W_Avg=0
return W_Avg
df_copy['sumpr']=df_copy.apply(test, axis=1)
df_copy
**|2020 | 2018 | 2019 | sumpr|**
|0 | 100 | 20 | 0 |
|1 | 30 | 10 | 270 |
|3 | 10 | 10 | 150 |
如果 table 看起来不像 table,我很抱歉。我无法在 Whosebug 中正确创建 table。
基本上对于特定行,如果
2020 = 2 ,
2018 =30 ,
2019 =10 ,
sumpr= 30 * 9 + 10*9 = 270
您的列名很可能是 字符串,而不是整数。
为了确认,运行 df_copy.columns
你应该会收到类似这样的信息:
Index(['2020', '2018', '2019'], dtype='object')
(注意列名周围的撇号)。
因此将您的列列表更改为:
column_list = ['2018', '2019']
在您的函数中,还将列名称更改为字符串:
df_copy['2020']
那么你的代码应该 运行.
你也可以运行更简洁的代码:
df_copy['sumpr'] = np.where(df_copy['2020'] != 0, (df_copy[column_list]
* weights).sum(axis=1), 0)