基于链条对熊猫行实施循环计算
我的代码块以下,
import pandas as pd
dat = (pd.DataFrame({'xx1' : [3,2,1], 'aa2' : ['qq', 'pp', 'qq'], 'xx3' : [4,5,6]})
.sort_values(by = 'xx1')
.reset_index(drop = True))
dat
for i in range(1, dat.shape[0]) :
if (dat.loc[i, 'aa2'] == 'qq') :
dat.loc[i, 'xx3'] = dat.loc[i - 1, 'xx3']
dat
第二个代码
for i in range(1, dat.shape[0]) :
if (dat.loc[i, 'aa2'] == 'qq') :
dat.loc[i, 'xx3'] = dat.loc[i - 1, 'xx3']
我想知道是否可以使用链条
在第一个块中使用链条
来实现 。意思是,我希望有以下的事情,
dat = (pd.DataFrame({'xx1' : [3,2,1], 'aa2' : ['qq', 'pp', 'qq'], 'xx3' : [4,5,6]})
.sort_values(by = 'xx1')
.reset_index(drop = True)
### implement the for loop here
)
任何指针都会非常有帮助
I have below block of codes,
import pandas as pd
dat = (pd.DataFrame({'xx1' : [3,2,1], 'aa2' : ['qq', 'pp', 'qq'], 'xx3' : [4,5,6]})
.sort_values(by = 'xx1')
.reset_index(drop = True))
dat
for i in range(1, dat.shape[0]) :
if (dat.loc[i, 'aa2'] == 'qq') :
dat.loc[i, 'xx3'] = dat.loc[i - 1, 'xx3']
dat
I am wondering if the second block of codes i.e.
for i in range(1, dat.shape[0]) :
if (dat.loc[i, 'aa2'] == 'qq') :
dat.loc[i, 'xx3'] = dat.loc[i - 1, 'xx3']
can be implemented using chain
in continuation with the first block. Means, I am hoping to have below sort of things,
dat = (pd.DataFrame({'xx1' : [3,2,1], 'aa2' : ['qq', 'pp', 'qq'], 'xx3' : [4,5,6]})
.sort_values(by = 'xx1')
.reset_index(drop = True)
### implement the for loop here
)
Any pointer will be very helpful
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以
分配
xx3
再次通过bask
qq
值并进行前进。由于循环从index = 1
开始,因此我们从index = 1
:输出启动掩码:输出:
You can
assign
xx3
again bymask
ing theqq
values and forward-filling it. Since the loop starts fromindex=1
, we start the mask fromindex=1
:Output: