python - 如何比较Python中数据框中的一行中的连续字符串值

标签 python python-3.x pandas data-cleaning

我想用同一行的前一个值填充特定行的值“0”。因此,逻辑是,如果该行的下一个值是“0”,那么同一行的前一个值将被复制到其中。

行的示例

enter image description here

和预期结果

enter image description here

该行是 pandas 数据框的一部分。请提供代码示例。我将感谢您的帮助。

谢谢

最佳答案

您可以使用replace()bfill()

import numpy as np

df['col_name'].replace(0, np.nan).bfill()

如果您的 0 是字符串,请使用

df['col_name'].replace("0", np.nan).bfill()

bfill 表示您将向后填充 NaN。您还可以使用 ffill() 填写转发信息

df['col_name'].replace(0, np.nan).ffill()

正如评论中所述,您还可以使用 to_replace arg 一次性设置所有内容:

df.col.replace(to_replace=0, method='ffill')
<小时/>

示例:

df = pd.DataFrame({'col': [1,2,3,0,5,6,7,0,9]})

col
0   1
1   2
2   3
3   0
4   5
5   6
6   7
7   0
8   9

df.col.replace(0, np.nan).bfill()

0    1.0
1    2.0
2    3.0
3    5.0
4    5.0
5    6.0
6    7.0
7    9.0
8    9.0

请注意,一旦np.nan是一个float,pandas可能会将该列解释为具有dtype float。但是,您始终可以使用 astype 将类型显式设置回 int

df.col.replace(0, np.nan).bfill().astype(int)

0    1
1    2
2    3
3    5
4    5
5    6
6    7
7    9
8    9

关于python - 如何比较Python中数据框中的一行中的连续字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51558647/

相关文章:

python - Python 和 Pandas 的问题 : Adding calculated column to dataframe that includes data from a function provides error

python - 如何调整透明背景图形的某些特征的颜色

python-3.x - 如何在两列中加载信息?

python - 如何迭代 Pandas 数据框并创建新列

python - 找到列表字典的值的最佳组合(也许使用 pandas)

python - 在 numpy 1.7.1 中,datetime64 和 vectorize 之间是否存在不良交互?

python - 开发基于线程 TCP 的管理界面的建议

python - 在 Python 中格式化两个数字

python - Python 中的 X.T 有什么作用?

python - Pandas 基于多个组求和行