python - 如何循环遍历 pandas 数据框并在条件下修改值?

标签 python pandas

我有这个 Pandas 数据框:

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 的列;否则为假:

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

enter image description here

现在像

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”。它应该看起来像这样:

enter image description here

我不确定这是否是我开发过程中的另一个步骤,或者这是否需要一种新方法。我读到如果我想在修改值时循环遍历数组,我应该使用 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/

相关文章:

python - 关于Python路径的问题

python - 如何使用 Python 打开和处理存储在 Google Cloud Storage 中的 CSV 文件

python - 如何使用相同的索引分割 pandas 数据框

python - Pandas - 使用另一个数据框过滤数据框

python - 如何在 python 上打印彩色的特定单词?

python - 如何在 PyQt4 脚本中导入和使用外部字典?

python - 导入 Pandas 会出现错误 AttributeError : module 'pandas' has no attribute 'core' in iPython Notebook

python - Pandas.read_excel : Unsupported format, 或损坏的文件:预期的 BOF 记录

python - Seaborn FacetGrid - 在最后一个子图之后放置单个颜色条

python - 我们如何才能更快地比较两个不同表之间的数据