0

I have the following dataframe:

print(inventory_df)

dt_op        Prod_1  Prod_2 ... Prod_n
10/09/18       0        8         0
10/09/18       5        0         2

11/09/18       4        0         0
11/09/18       0       10         0

...

And I would like to get:

print(final_df)

dt_op        Prod_1  Prod_2 ... Prod_n
10/09/18       5        8         2     
11/09/18       4       10         0 

...

I tried with:

final_df = inventory_df.drop_duplicates(subset=None, keep='first', inplace=False)

But it does not produce the desired output. How can I create final_df?

Alessandro Ceccarelli
  • 1,775
  • 5
  • 21
  • 41
  • do you want to drop all zeros from your dataframe even that they are assigned to different entries? – CIsForCookies Nov 20 '18 at 10:43
  • Possible duplicate of [Pandas group-by and sum](https://stackoverflow.com/questions/39922986/pandas-group-by-and-sum) – jpp Nov 20 '18 at 15:28

2 Answers2

1

You can use pandas groupby function with sum():

In [412]: inventory_df
Out[412]: 
      dt_op  Prod_1  Prod_2
0  10/09/18       0       8
1  10/09/18       5       0
2  11/09/18       4       0
3  11/09/18       0      10

In [413]: inventory_df.groupby('dt_op').sum()
Out[413]: 
          Prod_1  Prod_2
dt_op                   
10/09/18       5       8
11/09/18       4      10
Mayank Porwal
  • 33,470
  • 8
  • 37
  • 58
0

Just simulated the Stated DataFrame, you asked about the groupby + sum() across the rows.

Reproduced DataFrame:

>>> df
      dt_op  Prod_1  Prod_2  Prod_n
0  10/09/18       0       8       0
1  10/09/18       5       0       2
2  11/09/18       4       0       0

Using groupby around the columns axis=1(of dimension 1, which is what used to be columns) or simply df.groupby('dt_op').sum :

>>> df.groupby('dt_op').sum(axis=1)
          Prod_1  Prod_2  Prod_n
dt_op
10/09/18       5       8       2
11/09/18       4       0       0

However, you are looking for the literal sum() of rows across the columns:

>>> df['new_sum'] = df.sum(axis=1)
>>> df
      dt_op  Prod_1  Prod_2  Prod_n  new_sum
0  10/09/18       0       8       0        8
1  10/09/18       5       0       2        7
2  11/09/18       4       0       0        4
Karn Kumar
  • 8,518
  • 3
  • 27
  • 53