Python Forum
Python Pandas: How do I sumproduct by rows with an if condition?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python Pandas: How do I sumproduct by rows with an if condition?
#1
I am new to Python Pandas.

For each row, I want to do a sumproduct of certain columns only if column['2020'] !=0. I used the below code, but get error:

IndexError: ('index 2018 is out of bounds for axis 0 with size 27', 'occurred at index 0')

Pls help. Thank you
# 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 |
I am sorry if the table doesn't look like a table. I can't create a table properly here.

Basically for a particular row, if

2020 = 2 ,
2018 =30 ,
2019 =10 ,

sumpr= 30 * 9 + 10*9 = 270
Reply


Messages In This Thread
Python Pandas: How do I sumproduct by rows with an if condition? - by JaneTan - Jul-13-2021, 01:38 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Python Alteryx QS-Passing pandas dataframe column inside SQL query where condition sanky1990 0 690 Dec-04-2023, 09:48 PM
Last Post: sanky1990
  How is pandas modifying all rows in an assignment - python-newbie question markm74 1 653 Nov-28-2023, 10:36 PM
Last Post: deanhystad
  How to assign a value to pandas dataframe column rows based on a condition klllmmm 0 798 Sep-08-2022, 06:32 AM
Last Post: klllmmm
  The code I have written removes the desired number of rows, but wrong rows Jdesi1983 0 1,602 Dec-08-2021, 04:42 AM
Last Post: Jdesi1983
  How to combine multiple rows of strings into one using pandas? shantanu97 1 3,098 Aug-22-2021, 05:26 AM
Last Post: klllmmm
  Partial Matching Rows In Pandas DataFrame Query eddywinch82 1 2,338 Jul-08-2021, 06:32 PM
Last Post: eddywinch82
  Pandas DataFrame combine rows by column value, where Date Rows are NULL rhat398 0 2,082 May-04-2021, 10:51 PM
Last Post: rhat398
  Indexing [::-1] to Reverse ALL 2D Array Rows, ALL 3D, 4D Array Columns & Rows Python Jeremy7 8 6,962 Mar-02-2021, 01:54 AM
Last Post: Jeremy7
  Pandas: how to split one row of data to multiple rows and columns in Python GerardMoussendo 4 6,713 Feb-22-2021, 06:51 PM
Last Post: eddywinch82
  Pandas, Assign a value in a row, to another column based on a condition klllmmm 6 5,314 Oct-16-2020, 04:43 PM
Last Post: klllmmm

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020