当我运行下面的代码时,我收到错误:
TypeError:' NoneType'对象没有属性' getitem '
import pyarrow
import pandas
import pyarrow.parquet as pq
df = pq.read_table("file.parquet").to_pandas()
df = df.iloc[1:,:]
df = df.dropna (how="any", inplace = True) # modifies it in place, creates new dataset without NAN
average_age = df["_c2"].mean()
print average_age
数据框如下所示:
_c0 _c1 _c2
0 RecId Class Age
1 1 1st 29
2 2 1st NA
3 3 1st 30
如果我在调用dropna方法后打印df,我会得到“无”#。
如果没有' NA'那就不应该创建一个新的数据帧。在它,这将允许我得到平均年龄而不抛出错误?
答案 0 :(得分:1)
根据OP的评论,NA是字符串而不是NaN。所以dropna()
在这里并不好。过滤掉字符串值'NA'的许多可能选项之一是:
df = df[df["_c2"] != "NA"]
根据评论中@DJK的建议捕捉不精确匹配(例如使用尾随空格)的更好选择:
df = df[~df["_c2"].str.contains('NA')]
这个应删除任何字符串,而不仅仅是'NA':
df = df[df[“_c2”].apply(lambda x: x.isnumeric())]
答案 1 :(得分:1)
这也行,如果你的df中的NA是NaN(np.nan),这不会影响你得到列的平均值,只有你的NA是'NA',这是字符串
(df.apply(pd.to_numeric,errors ='coerce',axis=1)).describe()
Out[9]:
_c0 _c1 _c2
count 3.0 0.0 2.000000
mean 2.0 NaN 29.500000
std 1.0 NaN 0.707107
min 1.0 NaN 29.000000
25% 1.5 NaN 29.250000
50% 2.0 NaN 29.500000
75% 2.5 NaN 29.750000
max 3.0 NaN 30.000000
更多信息
df.apply(pd.to_numeric,errors ='coerce',axis=1)# all object change to NaN and will not affect getting mean
Out[10]:
_c0 _c1 _c2
0 NaN NaN NaN
1 1.0 NaN 29.0
2 2.0 NaN NaN
3 3.0 NaN 30.0