python - 根据其他列的值在 pandas 中创建新列

标签 python pandas dataframe

我正在处理以下数据框:

          p                      q 
   0      11                     2                            
   1      11                     2                  
   2      11                     2                  
   3      11                     3                  
   4      11                     3                  
   5      12                     2                  
   6      12                     2                  
   7      13                     2               
   8      13                     2            

我想创建一个新列,例如s,它从 0 开始并继续。这个新列基于“p”列,每当 p 更改时,“s”也应该更改。

对于前 4 行,“p”= 11,因此前 4 行的“s”列的值应为 0,依此类推...

以下是预期的 df:

     s             p         q 

 0   0             11        2         
 1   0             11        2         
 2   0             11        2          
 3   0             11        2          
 4   1             11        4           
 5   1             11        4           
 6   1             11        4           
 7   1             11        4           
 8   2             12        2           
 9   2             12        2           
 10  2             12        2           
 11  3             12        3           
 12  3             12        3        

最佳答案

您需要 diffcumsum(如果您希望 id 从 0 开始,则减一):

df["finalID"] = (df.ProjID.diff() != 0).cumsum()
df

enter image description here

更新,如果您想同时考虑voyg_idProjID,您可以使用OR两列差异的条件,这样无论哪一列发生变化,最终的 id 都会增加。

df['final_id'] = ((df.voyg_id.diff() != 0) | (df.proj_id.diff() != 0)).cumsum()
df

enter image description here

关于python - 根据其他列的值在 pandas 中创建新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43124833/

相关文章:

python-3.x - Pandas_datareader错误SymbolWarning:未能读取符号:“T”,替换为NaN

Python Pandas : Compute Mean, 标准偏差,并计算导入数据集的缺失值

python - Pandas 条形图总是创建一个空的子图

r - 字符串将值拆分为两列,然后将它们连接成一个新列

python - 从多索引 DataFrame 中搜索和处理数据

python - 将 pandas 数据框索引 reshape 为列

python - Plotly:如何根据悬停检索的值编辑文本输出?

python - 导入 xlrd 值 append 到列表

Python - 使用 Txt 文件数据绘制图形

python - QThread 信号发射两次