在python中,当在数据帧的另一列中发现重复值时,如何增加新列的值?

2024-06-06 09:15:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个CSV文件,看起来像:

Timestamp  Status
1501       Normal
1501       Normal
1502       Delay
1503       Received
1504       Normal
1504       Delay
1505       Received
1506       Received
1507       Delay
1507       Received

我想在dataframe中添加一个新的“Notif”列,它作为一个计数器变量出现,当它遇到“Status”列中的“Received”值时会有一个增量。 我希望输出看起来像:

^{pr2}$

我试着寻找这个问题的解决方案,各种来源都建议使用arcpy包来编写代码,但是我想在没有arcpy包的情况下也能正常工作,因为PyCharm似乎不支持arcpy包

还尝试使用numpy作为条件运算符,但似乎不起作用


Tags: 文件csvdataframestatus计数器解决方案增量timestamp
1条回答
网友
1楼 · 发布于 2024-06-06 09:15:11

使用df.iterrows迭代行,可以实现以下目的:

df['Notif'] = None
counter = 0
for idx, row in df.iterrows():
    if df.iloc[idx, 1] == "Received":
        counter +=1
    df.iloc[idx,-1] = "N" + str(counter)

print(df)

输出

^{pr2}$

相关问题 更多 >