如何根据条件推定 DataFrame 的某些包含或排除列的所有值?
How can all values of certain included or excluded columns of a DataFrame be impuded based on a condition?
假设我有一个简单的 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
布尔索引的列可能更少,因此您可以在构建布尔条件时删除列 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
假设我有一个简单的 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
布尔索引的列可能更少,因此您可以在构建布尔条件时删除列 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