我有一个叫dfA的数据,
ID Chronological Label
1 1 None
2 0 ONPEAPLFPH
3 0 JFECJGSQNS
4 1 None
5 1 None
6 0 MGMELTIVTJ
7 1 None
8 1 None
9 1 None 我希望将一个unique_id分配给列Chronological,这样每个后续的重复值都有一个“公共”unique_id。也就是说,我想要下列期望的输出,
ID Chronological Label unique_id
1 1 None 1
2 0 ONPEAPLFPH 2
3 0 JFECJGSQNS 3
4 1 None 4
5 1 None 4
6 0 MGMELTIVTJ 5
7 1 None 6
8 1 None 6
9 1 None 6我试过使用非矢量化的方法,使用for-循环,但是非常慢,
starting_index = 0
unique_id = 1
dfs = []
for cL in dfA['Label'].unique():
if cL != "None":
current_index = dfA[dfA['Label']==cL].index.values[0]
sliced_df = dfA.iloc[starting_index:current_index+1, :]
sliced_df_ = sliced_df.copy()
if len(sliced_df_)>=1:
sliced_df_['unique_id'] = unique_id
starting_index = current_index
unique_id += 1
dfs.append(sliced_df_)
df_concat = pd.concat(dfs, axis=0)有没有更有效的方法来解决这个问题?
发布于 2021-11-27 21:41:43
试试这个:
df['unique_id'] = (df['Chronological'].eq(0) |
(df['Chronological'] != df['Chronological'].shift())
).cumsum()输出:
ID Chronological Label unique_id
0 1 1 None 1
1 2 0 ONPEAPLFPH 2
2 3 0 JFECJGSQNS 3
3 4 1 None 4
4 5 1 None 4
5 6 0 MGMELTIVTJ 5
6 7 1 None 6
7 8 1 None 6
8 9 1 None 6https://stackoverflow.com/questions/70138882
复制相似问题