计数直到 Pandas 达到条件
我需要你的一些意见。我的想法是,我想看看需要多长时间(以行为单位)才能在
- 列
SUB_B1
中看到新值,并 - 在
SUB_B2
中看到新值
,即, 有多少步
-
SUB_A1
和SUB B1
之间以及 SUB A2
和SUB B2
之间
我已经构建了数据是这样的:(我按结果列对索引进行降序排序之后,我将索引 B 和 A 分开并将它们放置在新列中)
df.sort_values(['A','result'], ascending=[True,False]).set_index(['A','B'])
结果 | SUB_A1 | SUB_A2 | SUB_B1 | SUB_B2 | ||
---|---|---|---|---|---|---|
A | B | |||||
10_125 | 10_173 | 0.903257 | 10 | 125 | 10 | 173 |
10_332 | 0.847333 | 10 | 125 | 10 | 332 | |
10_243 | 0.842802 | 10 | 125 | 10 | 243 | |
10_522 | 0.836335 | 10 | 125 | 10 | 522 | |
58_941 | 0.810760 | 10 | 125 | 58 | 941 | |
... | ... | ... | ... | ... | ... | |
10_173 | 10_125 | 0.903257 | 10 | 173 | 10 | 125 |
58_941 | 0.847333 | 10 | 173 | 58 | 941 | |
1_941 | 0.842802 | 10 | 173 | 1 | 941 | |
96_512 | 0.836335 | 10 | 173 | 96 | 512 | |
10_513 | 0.810760 | 10 | 173 | 10 | 513 |
这是我到目前为止所做的:(编辑:我认为我需要迭代values[]
但是,我还没有设法循环到第一行之外...)
def func(group):
if group.SUB_A1.values[0] == group.SUB_B1.values[0]:
group.R1.values[0] = 1
else:
group.R1.values[0] = 0
if group.SUB_A1.values[0] == group.SUB_B1.values[1] and group.R1.values[0] == 1:
group.R1.values[1] = 2
else:
group.R1.values[1] = 0
df['R1'] = 0
df.groupby('A').apply(func)
预期结果:
结果 | SUB_B1 | SUB_B2 | R1 | R2 | ||
---|---|---|---|---|---|---|
A | B | |||||
10_125 | 10_173 | 0.903257 | 10 | 173 | 1 | 0 |
10_332 | 0.847333 | 10 | 332 | 2 | 0 | |
10_243 | 0.842802 | 10 | 243 | 3 | 0 | |
10_522 | 0.836335 | 10 | 522 | 4 | 0 | |
58_941 | 0.810760 | 58 | 941 | 0 | 0 | |
... | ... | ... | ... | ... | ... |
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您是否正在寻找这样的东西:
示例数据框:
现在这
导致
Are you looking for something like this:
Sample dataframe:
Now this
leads to
尝试使用 pandas.dataframe.iterrows.iterrows.iterrow href =“ https://pandas.pydata.org/docs/reference/api/pandas.dataframe.shift.html” rel =“ nofollow noreferrer”> pandas.dataframe.shift.shift 。
You can iterate through the dataframe and compare current row with the previous one, then add some condition:
Then repeat for B column.可以使用和一个自定义功能。
Try using pandas.DataFrame.iterrows and pandas.DataFrame.shift.
You can iterate through the dataframe and compare current row with the previous one, then add some condition:
Then repeat for B column. It is possible to get a better aproach using pandas.DataFrame.apply and a custom function.
噗!极好的!感谢你们的投入
Puh! Super! Thanks for the input you guys