gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 07:41:10 25 4
gpt4 key购买 nike

我有一个 CSV 文件,如下所示:

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

我想向数据帧添加一个新的“Notif”列,该列显示为计数器变量,并且当遇到“状态”列中的“已接收”值时会增加。我希望输出看起来像:

Timestamp  Status     Notif
1501 Normal N0
1501 Normal N0
1502 Delay N0
1503 Received N1
1504 Normal N1
1504 Delay N1
1505 Received N2
1506 Received N3
1507 Delay N3
1507 Received N4

我尝试寻找此问题的解决方案,并且各种来源建议使用 arcpy 包进行编码,但我想在没有它的情况下完成这项工作,因为 PyCharm 似乎不支持 arcpy 包

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

最佳答案

使用 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)

输出

+----+------------+-----------+-------+
| | Timestamp | Status | Notif |
+----+------------+-----------+-------+
| 0 | 1501 | Normal | N0 |
| 1 | 1501 | Normal | N0 |
| 2 | 1502 | Delay | N0 |
| 3 | 1503 | Received | N1 |
| 4 | 1504 | Normal | N1 |
| 5 | 1504 | Delay | N1 |
| 6 | 1505 | Received | N2 |
| 7 | 1506 | Received | N3 |
| 8 | 1507 | Delay | N3 |
| 9 | 1507 | Received | N4 |
+----+------------+-----------+-------+

关于python - 当 python 中数据帧的另一列中发现重复值时,如何增加新列的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56710907/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com