如何循环通过Pandas数据帧和修改条件下的值?

2024-04-20 02:56:15 发布

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

我有这个熊猫数据框:

df = pd.DataFrame(
    {
    "col1": [1,1,2,3,3,3,4,5,5,5,5]
    }
)
df

enter image description here

如果col1中的值不等于下一行中col1的值,我想添加另一列,该列显示“last”。它应该是这样的:

enter image description here

到目前为止,如果col1中的值不等于下一行中col1的值,则可以创建一个包含True的列;否则,我可以创建一个包含False的列:

^{pr2}$

enter image description here

现在有点像

^{3}$

很好,但这显然是错误的语法。我怎么能做到这一点?在


最后,我还想添加一些数字,指示一个值在这个值之前出现了多少次,而最后一个值总是标记为“last”。应该是这样的:

enter image description here

我不确定这是我开发的另一步,还是需要新的方法。我读到,如果我想在修改值时遍历数组,我应该使用apply()。但是,我不知道如何在这里面包含条件。你能帮助我吗?在

非常感谢!在


Tags: 数据方法标记falsetruedataframedf错误
3条回答

有一个办法。您可以根据col1中的下一个值是否与当前行的值相同来获得累积计数,定义一个自定义分组程序,并取^{}。然后使用类似的标准添加last,使用df.shift

g = df.col1.ne(df.col1.shift(1)).cumsum()
df['update'] = df.groupby(g).cumcount()
ix = df[df.col1.ne(df.col1.shift(-1))].index
# Int64Index([1, 2, 5, 6, 10], dtype='int64')
df.loc[ix,'update'] = 'last'

 col1 update
0      1      0
1      1   last
2      2   last
3      3      0
4      3      1
5      3   last
6      4   last
7      5      0
8      5      1
9      5      2
10     5   last

使用.shift查找事物的变化。然后您可以使用.where适当地屏蔽.fillna

s = df.col1 != df.col1.shift(-1)
df['Update'] = df.groupby(s.cumsum().where(~s)).cumcount().where(~s).fillna('last')

输出:

^{pr2}$

另外,update是一种数据帧的方法,因此应该避免将列命名为'update'

考虑到索引是递增的,(1)cuncount每个组,然后在每个组内取(2)max索引并设置字符串

group = df.groupby('col1')

df['last'] = group.cumcount()
df.loc[group['last'].idxmax(), 'last'] = 'last'
#or df.loc[group.apply(lambda x: x.index.max()), 'last'] = 'last'


    col1    last
0   1   0
1   1   last
2   2   last
3   3   0
4   3   1
5   3   last
6   4   last
7   5   0
8   5   1
9   5   2
10  5   last

相关问题 更多 >