我正在尝试使用 Python 计算数据框中对象变量的长度。我的很多变量都是带有缺失值的字符串,不幸的是,当我尝试计算缺失值的长度时,它显示为 3(因为它将“Nan”计算为 3 个字符值)。
这是我正在使用的代码:
df_string_mean_with_na = pd.DataFrame(df_string.applymap(len).astype(int).mean().to_dict(), index=[df_string.index.values[0]])
其中 df_string 是我的起始数据帧,我正在尝试计算每列值的平均长度。 我想将对象变量缺失值的长度计为0,有办法吗?
最佳答案
我认为你需要DataFrame.fillna
用于在计算长度
之前将缺失值替换为空字符串:
print (Table1)
A B C
0 hello hi NaN
1 good hi so
2 home hello no
测试缺失值:
print (Table1.isna())
A B C
0 False False True
1 False False False
2 False False False
df = Table1.fillna('').applymap(len).mean().to_frame().T
print (df)
A B C
0 4.333333 3.0 2.333333
详细信息:
print (Table1.fillna('').applymap(len))
A B C
0 5 2 0
1 4 2 2
2 4 5 2
如果缺失值是字符串
,请使用DataFrame.replace
:
print (Table1.isna())
A B C
0 False False False
1 False False False
2 False False False
df = Table1.replace('NaN', '').applymap(len).mean().to_frame().T
print (df)
A B C
0 4.333333 3.0 2.333333
关于python - 如何将字符串变量缺失值的长度计算为零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58197097/