繁体   English   中英

如何循环pandas数据帧并在条件下修改值?

[英]How to loop through pandas dataframe and modify value under condition?

我有这个pandas数据帧:

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

在此输入图像描述

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

在此输入图像描述

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

df["last_row"] = df["col1"].shift(-1)
df['last'] = df["col1"] != df["last_row"]
df = df.drop(["last_row"], axis=1)
df

在此输入图像描述

现在像

df["last_row"] = df["col1"].shift(-1)
df['last'] = "last" if df["col1"] != df["last_row"]
df = df.drop(["last_row"], axis=1)
df

会很好,但这显然是错误的语法。 我该如何设法做到这一点?


最后,我还想添加数字,表示在此之前值出现的时间,而最后一个值始终标记为“last”。 它应该如下所示:

在此输入图像描述

我不确定这是否是我开发中的另一个步骤,或者这是否需要一种新的方法。 我读过如果我想在修改值时循环遍历数组,我应该使用apply()。 但是,我不知道如何在此包含条件。 你能帮助我吗?

非常感谢!

这是一种方式。 您可以根据col1的下一个值是否与当前行的值相同,定义自定义DataFrameGroupBy.cumsum以及获取DataFrameGroupBy.cumsum来获取累积计数。 然后使用df.shift使用类似的标准添加last

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

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

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

使用.shift找到变化的地方。 然后你可以使用.where适当地掩盖然后.fillna

s = df.col1 != df.col1.shift(-1)
df['Update'] = df.groupby(s.cumsum().where(~s)).cumcount().where(~s).fillna('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

另外, update是DataFrames的一种方法,因此您应该避免命名列'update'

另一种可能的解决

df['update'] = np.where(df['col1'].ne(df['col1'].shift(-1)), 'last', 0)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM