0

I have temperature data that looks like this:

Date        State  Temperature (F)
2018-10-6   AL     15
2018-10-7   AL     45
2018-10-8   AL     67
2018-10-9   AL     25
2018-10-10  AL     55
2018-10-11  AL     77
.
.

I'd like to give a conditional statement that calculates a simple subtraction that creates a new column like this:

if df[Temperature, i] < 65:
     df[Calculation, i] = 65 - df[Temperature, i]
else:
     df[Calculation, i] = 0

So the output would be:

Date        State  Temperature (F)   Calculation
2018-10-6   AL     15                0
2018-10-7   AL     45                0
2018-10-8   AL     67                2
2018-10-9   AL     25                0
2018-10-10  AL     55                0
2018-10-11  AL     77                12
.
.

I'm not sure how to simply iterate over the column with this type of loop.

Is there an easy way to do this?

HelloToEarth
  • 2,027
  • 3
  • 22
  • 48
  • 1
    You don't iterate, you might as well be using base Python otherwise. `df['Calculation'] = np.where(df['Temperature'] < 65, 65 - df['Temperature'], 0)` – roganjosh Jan 07 '19 at 20:48

1 Answers1

3

IIUC clip_lower

df['Temperature(F)'].sub(65).clip_lower(0)
Out[377]: 
0     0
1     0
2     2
3     0
4     0
5    12
Name: Temperature(F), dtype: int64

UPDATE 14.05.2021:

instead of clip_lower(0) the documentation for pandas 0.25.3 https://pandas.pydata.org/pandas-docs/version/0.25.3/reference/api/pandas.DataFrame.clip_lower.html states:

Deprecated since version 0.24.0: Use clip(lower=threshold) instead.

so the answer would be:

df['Temperature (F)'].sub(65).clip(lower = 0)
Out[6]:
0     0
1     0
2     2
3     0
4     0
5    12
Name: Temperature (F), dtype: int64
shehryar
  • 98
  • 1
  • 8
BENY
  • 317,841
  • 20
  • 164
  • 234