gpt4 book ai didi

python - “NoneType”对象没有属性 'fillna'错误

转载 作者:行者123 更新时间:2023-12-01 07:57:12 32 4
gpt4 key购买 nike

我在以下代码中遇到错误。无法理解为什么。在代码的最后一行出现错误。请告知必须采取哪些措施来纠正它。除此之外 df.isna().any() 也不起作用。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

%matplotlib inline

data = pd.read_csv('BlackFriday.csv')
df = pd.DataFrame(data)

df.info()
df.describe()
df.head()

#To check the unique values of Product Categories 2, 3 and then assign a default value accordingly for NaN's

Product_Category_2 = df['Product_Category_2'].unique()
Product_Category_3 = df['Product_Category_3'].unique()
print('Product_Category_2', Product_Category_2)
print('Product_Category_3', Product_Category_3)

df = df.fillna(0, inplace=True)




---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-16-7f28e582ea84> in <module>()
1 #We can replace the NaN's with 0.
----> 2 df = df.fillna(0, inplace=True)
3

AttributeError: 'NoneType' object has no attribute 'fillna'


最佳答案

我看到的第一个问题,pd.read_csv 已经创建了一个数据帧,因此您不需要再次将其分配给数据帧。

然后,您的主要问题是:您不能在同一赋值操作中同时使用 inplace=Truedf=df.fillna()inplace=True 导致 fillna 方法返回 None,然后将其分配给 df。这可行,并将您的变量分配给 None,但不会导致您看到的错误,除非您尝试重新运行该行代码或在运行后引用数据帧。

df=pd.DataFrame({'a':[1,2,3,4,5],'b':[6,7,8,9,0],'c':[None,None,1,2,None]})

a b c
0 1 6 NaN
1 2 7 NaN
2 3 8 1.0
3 4 9 2.0
4 5 0 NaN

正确:

或者

df.fillna(0,inplace=True)

或者

df=df.fillna(0)
df
a b c
0 1 6 0.0
1 2 7 0.0
2 3 8 1.0
3 4 9 2.0
4 5 0 0.0

错误:

df=df.fillna(0, inplace=True)

print(df)
None

关于python - “NoneType”对象没有属性 'fillna'错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55910397/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com