【发布时间】:2018-01-13 23:54:20
【问题描述】:
我想将未对齐或缺失的(NaN、Inf、-Inf)值视为 1 或 0。
df1 = pd.DataFrame({"x":[1, 2, 3, 4, 5],
"y":[3, 4, 5, 6, 7]},
index=['a', 'b', 'c', 'd', 'e'])
df2 = pd.DataFrame({"y":[1, NaN, 3, 4, 5],
"z":[3, 4, 5, 6, 7]},
index=['b', 'c', 'd', 'e', 'f'])
上面的代码结果如下
df1 * df2
x y z
a NaN NaN NaN
b NaN 4.0 NaN
c NaN NaN NaN
d NaN 18.0 NaN
e NaN 28.0 NaN
f NaN NaN NaN
我想忽略 NaN,并将未对齐的值视为左侧或右侧 DF 或两者中的 1。
例如
案例 1:用 1 替换 df1 中缺失或未对齐的值
df1 * df2
x y z
a 1 3 NaN
b 2 4.0 NaN
c 3 5 NaN
d 4 18.0 NaN
e 5 28.0 NaN
f NaN NaN NaN
案例 2:用 1 替换 df2 中缺失或未对齐的值
df1 * df2
x y z
a NaN NaN NaN
b NaN 4.0 3
c NaN NaN 4
d NaN 18.0 5
e NaN 28.0 6
f NaN 5 7
案例 3:如果另一个 DF 中有值,则将任何缺失或未对齐的值替换为 1。
df1 * df2
x y z
a 1 3 NaN
b 2 4.0 3
c 3 5 4
d 4 18.0 5
e 5 28.0 6
f NaN 5 7
在 addison 的情况下,我想将缺失或未对齐的值视为 0。
【问题讨论】:
标签: python pandas dataframe indexing missing-data