Home > Net >  Pandas dataframe sum if [duplicate]
Pandas dataframe sum if [duplicate]

Time:09-16

I have the following df:

d = {'col1': [0.1, 0.2, 1.2]}
dataframe = pd.DataFrame(data=d)

I want to sum up every value smaller than 1. As I get as a result 0.3 in this case. How to do it ideally?

CodePudding user response:

Try this:

dataframe.loc[dataframe['col1'] < 1, 'col1'].sum()

Or:

dataframe.mask(dataframe['col1'] > 1).sum()['col1']

CodePudding user response:

You can filter out the higher than 1 values and sum:

dataframe.where(dataframe['col1'].lt(1))['col1'].sum()

CodePudding user response:

Try this:

dataframe[dataframe['col1'].lt(1.0)]['col1'].sum()
  • Related