在我的工作流程中,有多个 CSV,其中包含四列 OID、值、计数、unique_id
。我试图弄清楚如何在 unique_id
列下生成增量值。使用 apply()
,我可以执行类似 df.apply(lambda x : x + 1) #where x = 0
的操作,它将产生 下的所有值>unique_id
as 1。但是,我对如何使用 apply()
在每一行中为特定列生成增量值感到困惑。
# Current Dataframe
OID Value Count unique_id
0 -1 1 5 0
1 -1 2 46 0
2 -1 3 32 0
3 -1 4 3 0
4 -1 5 17 0
# Trying to accomplish
OID Value Count unique_id
0 -1 1 5 0
1 -1 2 46 1
2 -1 3 32 2
3 -1 4 3 3
4 -1 5 17 4
示例代码(我知道语法不正确,但这大约是我想要完成的任务):
def numbers():
for index, row in RG_Res_df.iterrows():
return index
RG_Res_df = RG_Res_df['unique_id'].apply(numbers)
最佳答案
不要循环你可以直接分配一个numpy数组来生成id,这里使用np.arange
并传递行数,该行数将是 df.shape[0]
In [113]:
df['unique_id'] = np.arange(df.shape[0])
df
Out[113]:
OID Value Count unique_id
0 -1 1 5 0
1 -1 2 46 1
2 -1 3 32 2
3 -1 4 3 3
4 -1 5 17 4
或者使用RangeIndex
的纯pandas方法,这里默认的start
是0
,所以我们只需要传递stop=df。形状[0]
:
In [114]:
df['unique_id'] = pd.RangeIndex(stop=df.shape[0])
df
Out[114]:
OID Value Count unique_id
0 -1 1 5 0
1 -1 2 46 1
2 -1 3 32 2
3 -1 4 3 3
4 -1 5 17 4
关于python - Pandas Dataframe - 生成增量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42561042/