【问题标题】:How can all values of certain included or excluded columns of a DataFrame be impuded based on a condition?如何根据条件估算 DataFrame 某些包含或排除列的所有值?
【发布时间】:2017-10-04 00:29:36
【问题描述】:

假设我有一个简单的 DataFrame:

import pandas as pd

df = pd.DataFrame.from_dict(
        {
            'foo': [0.00, 0.31, 0.45],
            'bar': [1.00, 0.55, 3.01],
            'qux': [0.30, 4.10, 2.78]
        },
        orient = 'index'
     )

这里是:

       0     1     2
qux  0.3  4.10  2.78
foo  0.0  0.31  0.45
bar  1.0  0.55  3.01

我可以通过这种方式将DataFrame中小于1的所有值更改为其他值(0):

df[df < 1] = 0

这会导致:

       0    1     2
qux  0.0  4.1  2.78
foo  0.0  0.0  0.00
bar  1.0  0.0  3.01

我如何将这样的更改应用于除第 2 列之外的所有列?这将导致以下结果:

       0    1     2
qux  0.0  4.1  2.78
foo  0.0  0.0  0.45
bar  1.0  0.0  3.01

【问题讨论】:

标签: python pandas dataframe imputation


【解决方案1】:

布尔索引的列可能会更少,因此您可以在构造布尔条件时删除列 2

df[df.drop(2, axis=1) < 1] = 0

df
#         0   1    2
#foo    0.0 0.0 0.45
#qux    0.0 4.1 2.78
#bar    1.0 0.0 3.01

df[df.drop(1, axis=1) < 1] = 0

df
#         0    1       2
#foo    0.0 0.31    0.00
#qux    0.0 4.10    2.78
#bar    1.0 0.55    3.01

【讨论】:

  • 我找不到更好的解决方案 ;-)
猜你喜欢
  • 2021-05-13
  • 2022-06-28
  • 1970-01-01
  • 2018-02-01
  • 2022-07-05
  • 1970-01-01
  • 2021-02-04
  • 1970-01-01
  • 2015-10-09
相关资源
最近更新 更多