gpt4 book ai didi

python - 用下一行替换数据框元素的数据

转载 作者:太空宇宙 更新时间:2023-11-04 07:32:27 25 4
gpt4 key购买 nike

我有以下数据框:

0  Symbol   DataDiscriminator   Open
1 AKAM Summary -
2 AKAM Lot 2017-05-12, 16:20:00
3 APA Summary -
4 APA Lot 2017-03-31, 16:20:00
5 APA Lot 2017-03-24, 16:20:00

我想将 DataDiscriminatorOpen 元素的值设置为下一行的日期 = "Summary",然后删除 DataDiscriminator = "Lot"行得到:

0  Symbol   DataDiscriminator   Open
1 AKAM Summary 2017-05-12
3 APA Summary 2017-03-31
...

目前的工作逻辑是:

for i, row in s.iterrows():
if s.DataDiscriminator[i] == "Summary":
o = s.Open[i+1] # Get the next row's Open data
s = s.set_value(i, "Open", o[0:10]) # Slice out the time in the new Open data
s = s[s.DataDiscriminator == "Summary"] # Keep only the Summary rows in the dataset

是否有更好的矢量化方式来实现这一目标?

最佳答案

Shift 是执行此操作的标准矢量化方式:

>>> df.loc[ df.DataDiscriminator=='Summary','Open'] = df.Open.shift(-1)
>>> df = df[ df.DataDiscriminator=='Summary' ]

Symbol DataDiscriminator Open
0 AKAM Summary 2017-05-12, 16:20:00
2 APA Summary 2017-03-31, 16:20:00

关于python - 用下一行替换数据框元素的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44737540/

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