我有这个 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
中的下一个值是否与当前行的值相同来获取累积计数,定义自定义 grouper,并取 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
关于python - 如何循环遍历 pandas 数据框并在条件下修改值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55870877/