[英]Pandas: for each last row in a group, assign a column a value
如何为组的最后一行分配我想要的值(假设我已经对 DF 进行了排序)?
# data
df = pd.DataFrame([['a', 1], ['a', 2], ['b', 1], ['b', 2]],
columns=['colA', 'colB'])
# create a new col
df['colC'] = 'Not Current'
# my attempt -- groupby col of interest, get last row, apply value to 'colC' column
df.loc[df.reset_index().groupby('colA').tail(1), 'colC'] = 'Current'
您可以使用通话index
进行修复
df.loc[df.groupby('colA').tail(1).index, 'colC'] = 'Current'
df
Out[105]:
colA colB colC
0 a 1 Not Current
1 a 2 Current
2 b 1 Not Current
3 b 2 Current
使用loc
与duplicated
:
df['colC'] = 'Not Current'
not_last_rows = df['colA'].duplicated(keep='last')
df.loc[~not_last_rows, 'colC'] = 'Current'
或者在你的情况下, np.where
:
not_last_rows = df['colA'].duplicated(keep='last')
df['colC'] = np.where(not_last_rows, 'Not Current', 'Current')
输出:
colA colB colC
0 a 1 Not Current
1 a 2 Current
2 b 1 Not Current
3 b 2 Current
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.