Lost1
Lost1

Reputation: 1062

combining rows in pandas dataframe

I have the data frame

Date         CUSIP   Asset   Liability
01-01-1990     A       1        NaN
01-01-1990     A      Nan        2
02-01-1990     A       3         2
01-01-1990     B      Nan        2
01-01-1990     B       1         2

Is there anyway of combining this such that it becomes:

Date         CUSIP   Asset   Liability
01-01-1990     A       1         2
02-01-1990     A       3         2
01-01-1990     B       1         2

The way I came up with is to use groupby(["CUSIP", Date]).agg(function)

where I apply a function where the max(nan, 3) = 3.

Is there a simpler way?

Upvotes: 0

Views: 266

Answers (1)

Alexander
Alexander

Reputation: 109546

>>> df.groupby(['Date', 'CUSIP']).apply(lambda group: group.ffill().bfill()).drop_duplicates()
         Date CUSIP Asset  Liability
0  01-01-1990     A     1          2
2  02-01-1990     A     3          2
3  01-01-1990     B     1          2

Upvotes: 1

Related Questions