python - Pandas Dataframe - 生成增量值

标签 python python-2.7 pandas

在我的工作流程中,有多个 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方法,这里默认的start0,所以我们只需要传递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/

相关文章:

python - 有条件的 pandas 中两个数据帧的复杂 Map 操作

python - django-models、views.py 和外键分配模板

python - 我们如何使用 pandas 在 python 中使用 Coalesce 来处理多个数据帧

python pandas,替换函数一次应用于多个数据帧

python - 条件下的 DataFrameGroupBy diff()

python - matplotlib:使图例出现在其他子图上方

python - 如何让正则表达式返回字符串(而不是正则表达式对象)?

windows - 从网页自动下载文件

python - 读取 .txt 文件中的数据(不包括页眉和页脚)

python - 在 Windows 上用 open(filename, 'w') 找不到我的文件