使用 df.dropna() 返回 NoneType 对象

imp*_*ity 2 python python-3.x pandas

我有一段代码,如下所示:

import pandas as pd
file = pd.read_csv("/my/path/to/spreadsheet.csv", index_col=0)
file = file.dropna(how="any", inplace=True)
file = file.fillna("", inplace=False)
print(file)
Run Code Online (Sandbox Code Playgroud)

预期输出:

       Profit ($)  Spendings ($)      Total Profit  EOY Profit ($)
Month                                                                       
Jan           200             80               120            3150
Feb           310             50               260                          
Mar           250             40               210                          
Apr           170             70               100                          
May           650            200               450                          
Jun           180            150                30                          
Jul           530            160               370                          
Aug           610            270               340                          
Sep           470            180               290                          
Oct           680            290               390                          
Nov           570            310               260                          
Dec           600            270               330                          
Run Code Online (Sandbox Code Playgroud)

电流输出:

回溯(最近一次调用最后):文件“/my/path/to/OpenSheet.py”,第5行,文件= file.fillna(“”,inplace = False)AttributeError:'NoneType'对象没有属性'fillna '

我明白这意味着当我file = file.dropna(how="any", inplace=True)这样做时它以某种方式变成了一个NoneType对象,但这是为什么呢?

另外,谁能告诉我如何获得预期的输出?

C.N*_*ivs 5

这是因为inplace=True参数就地修改了参数,这意味着函数返回None。将其更改为

import pandas as pd
file = pd.read_csv("/my/path/to/spreadsheet.csv", index_col=0)
file.dropna(how="any", inplace=True)
file = file.fillna("", inplace=False)
print(file)
Run Code Online (Sandbox Code Playgroud)

此外,看起来您的EOY Profit列将导致几乎所有行都被删除:

file.dropna(how="any", inplace=True)

file
  EOY_Profit Month Profit Spendings Total_Profit
0       3150   Jan    200        80          120
Run Code Online (Sandbox Code Playgroud)

所以我会完全避开这条dropna线

file = pd.read_csv("/my/path/to/spreadsheet.csv", index_col=0)
file = file.fillna("", inplace=False)
    EOY_Profit Month Profit Spendings Total_Profit
0        3150   Jan    200        80          120
1               Feb    310        50          260
2               Mar    250        40          210
3               Apr    170        70          100
4               May    650       200          450
5               Jun    180       150           30
6               Jul    530       160          370
7               Aug    610       270          340
8               Sep    470       180          290
9               Oct    680       290          390
10              Nov    570       310          260
11              Dec    600       270          330
Run Code Online (Sandbox Code Playgroud)