我有以下数据框:
EO EW Inc20 Inc100
bike 6 4.0 7 5
other 1 NaN 1 1
我想将NaN值替换为零。并且我编写了以下代码:
for column in df:
df.loc[df.isnull().any(axis=1), column] = 0
df
它运作良好,并将NaN更改为零,但它也更改了第一列的值。 所以我得到这个结果:
EO EW Inc20 Inc100
bike 6 4.0 7 5
other 0 0 1 1
但是我想要拥有:
EO EW Inc20 Inc100
bike 6 4.0 7 5
other 1 0 1 1
答案 0 :(得分:0)
如果仅需替换(如果存在),则使用class PkceChallenge {
random(length, mask) {
let result = "";
let randomIndices = new Int8Array(length);
window.crypto.getRandomValues(randomIndices);
const byteLength = 256
const maskLength = Math.min(mask.length, byteLength);
const scalingFactor = byteLength / maskLength;
for (var i = 0; i < length; i++) {
result += mask[Math.floor(Math.abs(randomIndices[i]) / scalingFactor)];
}
return result;
}
base64UrlEncode(array) {
return btoa(String.fromCharCode.apply(null, new Uint8Array(array)))
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/, '');
}
generateVerifier(length) {
const mask = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";
return this.random(length, mask);
}
generateChallenge(length = 43) {
this.verifier = this.generateVerifier(length);
const encoder = new TextEncoder();
const data = encoder.encode(this.verifier);
return window.crypto.subtle.digest('SHA-256', data).then(array => { return { code_challenge: this.base64UrlEncode(array), code_verifier: this.verifier }; });
}
}
用DataFrame.isna
为DataFrame.loc
计算缺失值并用sum
过滤DataFrame.mask
中的掩码:
fillna
或仅对每列中的一个缺失值创建掩码,将掩码链接起来并替换为DataFrame.fillna
:
print (df)
EO EW Inc20 Inc100
bike 6 4.0 7 5.0
other 1 NaN 1 NaN
other 1 NaN 1 1.0
m = df.isna().sum().eq(1)
df.loc[:, m] = df.loc[:, m].fillna(0)
m = df.isna() & df.isna().sum().eq(1)
df = df.mask(m, 0)
因为{{3}}替换了所有缺失的值:
print (df)
EO EW Inc20 Inc100
bike 6 4.0 7 5.0
other 1 NaN 1 0.0
other 1 NaN 1 1.0
答案 1 :(得分:0)
如果只想更改一列的值,请添加到jezrael的答案中
df['EW'].fillna(0, inplace=True)