Consider a data frame df
date time isopen isclose openlate closeearly
20200201 0920 Y N Y N
20200201 1645 N Y N Y
20200202 0900 Y N N N
20200202 1650 N Y N Y
20200203 0910 Y N Y N
20200203 1700 N Y N N
openlate
and closeearly
were computed from time and isopen/isclose
columns.
我想按日期展平,有类似
date openlate closeearly
20200201 Y Y
20200202 N Y
20200203 Y N
Basically to collapse multiple rows by a groupby
, partition or window function, then choose a logic which value to keep among the rows. I do have this situation on many occasions.
df.groupby("date")..['openlate' take 'Y' if any df["openlate"] in group is 'Y', else 'N';
'closeearly' takes 'Y' if any df["closeearly"] in the group is 'Y', else 'N']
You can use the
DataFrameGroupBy.agg
method. It allows you to apply a custom function to aggregate each group. In fact it even allows you to pass a dictionary mapping each column to a different function.在您的情况下: