如何将字符串变量缺失值的长度计为零?
How to count length of missing values for string variables as zero?
我正在尝试使用 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
在计数之前将缺失值替换为空字符串 length
:
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
如果缺失值为 strings
使用 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 计算数据框中对象变量的长度。我的很多变量都是带有缺失值的字符串,不幸的是,当我尝试计算缺失值的长度时,它显示为 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
在计数之前将缺失值替换为空字符串 length
:
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
如果缺失值为 strings
使用 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