python - Pandas :用另一列的值替换零值

标签 python pandas

如何用另一列的同一行的值替换列中的零值,其中该列的前一行值为零,即仅在尚未遇到非零的情况下替换? 例如:给定一个包含列 abc 的数据框:

+----+-----+-----+----+
|    |   a |   b |  c |
|----+-----+-----|----|
|  0 |   2 |   0 |  0 |
|  1 |   5 |   0 |  0 |
|  2 |   3 |   4 |  0 |
|  3 |   2 |   0 |  3 |
|  4 |   1 |   8 |  1 |
+----+-----+-----+----+

a 的值替换 bc 中的零值,其中先前的值为零

+----+-----+-----+----+
|    |   a |   b |  c |
|----+-----+-----|----|
|  0 |   2 |   2 |  2 |
|  1 |   5 |   5 |  5 |
|  2 |   3 |   4 |  3 |
|  3 |   2 |   0 |  3 | <-- zero in this row is not replaced because of  
|  4 |   1 |   8 |  1 |     non-zero value (4) in row before it.
+----+-----+-----+----+

最佳答案

In [90]: (df[~df.apply(lambda c: c.eq(0) & c.shift().fillna(0).eq(0))]
    ...:    .fillna(pd.DataFrame(np.tile(df.a.values[:, None], df.shape[1]),
    ...:                         columns=df.columns, index=df.index))
    ...:    .astype(int)
    ...: )
Out[90]:
   a  b  c
0  2  2  2
1  5  5  5
2  3  4  3
3  2  0  3
4  1  8  1

解释:

In [91]: df[~df.apply(lambda c: c.eq(0) & c.shift().fillna(0).eq(0))]
Out[91]:
   a    b    c
0  2  NaN  NaN
1  5  NaN  NaN
2  3  4.0  NaN
3  2  0.0  3.0
4  1  8.0  1.0

现在我们可以用下面 DF 中的相应值填充 NaN(它构建为 3 个连接的 a 列):

In [92]: pd.DataFrame(np.tile(df.a.values[:, None], df.shape[1]), columns=df.columns, index=df.index)
Out[92]:
   a  b  c
0  2  2  2
1  5  5  5
2  3  3  3
3  2  2  2
4  1  1  1

关于python - Pandas :用另一列的值替换零值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44259314/

相关文章:

Python Pandas Dataframe 按值从列表中删除行

python - SessionNotCreatedException : Message: Unable to create new service: ChromeDriverService with Selenium 3. 14.0 和 Python 3.7.3

python - 如何映射多列python

python - 在 Pandas 中,如何连续计算连续的正数和负数?

python - 从 Pandas 中的括号中提取

python - Pandas:根据目标分布从 DataFrame 中采样

python - DataFrame:具有有效值运行总和的 fillna()

python - 为什么我需要在 setup.py 中包含子包

Python rstrip() 工作起来很奇怪

Python Pandas : Overwriting an Index with a list of datetime objects