[英]Exception has occurred: TypeError object of type 'float' has no len()
我正在尝试执行此代码
import pandas as pd
df_schema = pd.read_csv('survey_results_schema.csv')
df_results = pd.read_csv('survey_results_public.csv', index_col='Respondent')
print(df_results['Country'].apply(len))
我应该得到这个:
Respondent
1 14
2 22
3 8
...
但我不断收到此错误,我不知道如何解决它:
Exception has occurred: TypeError
object of type 'float' has no len()
如果我们执行这一行print(df_results['Country'])
,我们会得到这个
Respondent
1 United Kingdom
2 Bosnia and Herzegovina
3 Thailand
4 United States
5 Ukraine
...
88377 Canada
88601 NaN
88802 NaN
88816 NaN
88863 Spain
我的代码有什么问题?
您的问题可能是您的数据中有 NaN。 NaN 类型被识别为浮点数,因此这是您出错的原因。
以下代码将为每个 NaN 值设置 0,否则将设置该值的 len:
print(df_results['Country'].apply(lambda x: 0 if pd.isna(x) else len(x)))
更好的方法是在使用 Dataframe 之前清除您的 null 值。 You can use the dropna function for that: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.dropna.html#pandas.DataFrame.dropna
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.