将fillna应用于数据帧列表

2024-09-20 05:41:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在数据帧列表上应用fillna(0)方法,但是for循环似乎没有起作用。基本上,我在一个列表中有4个数据帧,如下所示

Tox=[toxsnaus,toxvom,toxwt,toxanor]

现在,这个列表中的每个数据帧都有一些我想用零填充的nan值,但是当我尝试用for循环填充它们时

for tx in Tox: #fill all nans
    tx=tx.fillna(0)

这实际上并不替换这些值,而是在循环迭代中更改tx的值。我如何获得它,使fillna(0)实际应用于数据帧而不是迭代器tx

谢谢


Tags: 数据方法intox列表fornanall
2条回答

如果您填写了NAN,您的代码应该可以正常工作,即:

for tx in Tox: # fill all nans
    tx.fillna(0, inplace=True)

请注意,不需要指定任务。有关详细信息,请参见docs

您需要的是将其应用回原始数据帧

import pandas as pd
import numpy as np

df1 = pd.DataFrame({'col': [1,1,np.nan],})
df2 = pd.DataFrame({'col': [1,np.nan, 1],})

dfs = [df1, df2]

for i, tx in enumerate(dfs):
    dfs[i] = tx.fillna(0)

for tx in dfs:
    print(tx)

   col
0  1.0
1  1.0
2  0.0
   col
0  1.0
1  0.0
2  1.0

相关问题 更多 >