我有一个 csv.data 并想添加一个新列("new")。在这个新专栏中,我喜欢将“循环”中的两个最低值设为 1。其余的应该是0。应对“id”中的每组数字执行此过程。结果应该如下图所示。(这只是一个例子。就我而言,我有更多的数据)希望有人能帮助我。
id循环新 1 1 1 1 2 1 1 3 0 2 1 1 2 2 1 2 3 0 3 1 1 3 2 1 3 3 0
请您参考如下方法:
您可以使用 SeriesGroupBy.nsmallest与 numpy.where :
idx = df.groupby('id')['cycle'].nsmallest(2).reset_index(drop=True, level=0).index
print (idx)
Int64Index([0, 1, 3, 4, 6, 7], dtype='int64')
df['new1'] = np.where(df.index.isin(idx), 1, 0)
print (df)
id cycle new new1
0 1 1 1 1
1 1 2 1 1
2 1 3 0 0
3 2 1 1 1
4 2 2 1 1
5 2 3 0 0
6 3 1 1 1
7 3 2 1 1
8 3 3 0 0
