rpb
rpb

Reputation: 3299

Update value only on even or odd rows using mask in Pandas

The objective is to create a new set of column with the odd and even row resulting from np.floor and np.ceil operation, respectively.

The idea was to first np.floor for all rows.Then, the output of np.ceil only for the even rows.

I envision this can be done something along the code lines below

import pandas as pd

df = pd.DataFrame ( [6114.26221,
                     6114.90137,
                     6145.16943,
                     6183.22803,
                     6202.06592,
                     6202.38037,
                     6202.93750,
                     6203.21387,
                     ], columns=['onset'] )
df ['round'] = df ['onset'].apply ( np.floor )

df ['round'].where ( df % 2 != 0, df ['onset'].apply ( np.ceil ) )

However, the compiler return

AssertionError

Expected output

6114.00000
6115.00000
6145.00000
6184.00000
6202.00000
6203.00000
6202.00000
6204.00000

Upvotes: 0

Views: 1335

Answers (1)

Chris
Chris

Reputation: 29742

One way using numpy.where:

df["round"] = np.where(df.index % 2, np.ceil(df["onset"]), np.floor(df["onset"]))

Output:

        onset   round
0  6114.26221  6114.0
1  6114.90137  6115.0
2  6145.16943  6145.0
3  6183.22803  6184.0
4  6202.06592  6202.0
5  6202.38037  6203.0
6  6202.93750  6202.0
7  6203.21387  6204.0

Upvotes: 1

Related Questions