python - 根据索引列表更改 Pandas 列的值

标签 python pandas dataframe

我有一个 df,其中有两列 uidp,我想向现有的 df 添加一个新列或创建一个全新的 df其值基于“uid”列和索引 x 列表的值的列:

x = [2, 9, 12]

x 包含我应该生成新 id 的索引,新 id 是以前的 id 的增量。因此,会有两种情况,每当遇到列表 x 中的索引时,都会生成新的 id,并且每当 uid 列中的 id 发生变化时,都会再次生成新的 id,如下所示:

     uid       expected_newid     p     

0      1       1                 10     
1      1       1                 23    
2      1       2                 20  #new id generated at index 2    
3      1       2                 40
4      2       3                 21  #newid generated as "uid" changes
5      2       3                 89
6      2       3                 45
7      3       4                 50
8      3       4                 32
9      3       5                 76  #new id generated at index 9
10     3       5                 71 
11     3       5                 90
12     3       6                 56  #new id generated at index 12
13     3       6                 87

如果有什么不清楚的地方请告诉我。

只要 uid 使用以下代码更改,我就可以管理生成新 ID 的情况

df['newid'] = (df.uid.diff() != 0).cumsum()

但它还应该在列表 x 中提到的索引处生成 newid,如“expected_newid”列所示

最佳答案

IIUC,您可以简单地扩展您当前使用的条件,以包括索引在 x 中的可能性,使用“或”(此处写为 | ):

In [12]: df["newid"] = ((df.uid.diff() != 0) | (df.index.isin(x))).cumsum()

In [13]: df
Out[13]: 
    uid  expected_newid   p  newid
0     1               1  10      1
1     1               1  23      1
2     1               2  20      2
3     1               2  40      2
4     2               3  21      3
5     2               3  89      3
6     2               3  45      3
7     3               4  50      4
8     3               4  32      4
9     3               5  76      5
10    3               5  71      5
11    3               5  90      5
12    3               6  56      6
13    3               6  87      6

关于python - 根据索引列表更改 Pandas 列的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44619536/

相关文章:

pandas - 如何删除时间戳中的 freq ='W-FRI' 部分

csv - 将 csv 文件读取为 spark 数据帧

java - 识别父数据框中不存在于java子集数据框中的记录

python - ImageChops.difference 的定义

python - pytorch 如何计算简单线性回归模型的梯度?

python - 从空列表中弹出

python - 在 Tensorflow 中有效计算成对排名损失函数

python - 为什么我在 Pandas 重新分配中得到 weakref?

python - 如何计算 coskew 和 cokurtosis

r - 提取两个重叠栅格的数据