【问题标题】:Fill NaN values in DataFrame with generic values用通用值填充 DataFrame 中的 NaN 值
【发布时间】:2020-12-18 01:13:45
【问题描述】:

使用 Python3.7 和当前最新版本的 Pandas。 我有一个具有以下数据类型的数据框:[category, float, object(text)] 我要做的就是一次为整个数据框填充 NaN 值。

我自己做的是逐一浏览每一列(一次数百)并将列名分组到按数据类型组织的列表中。然后使用pd.astype(datatype) 设置该列列表。这是非常乏味和低效的,因为我仍然继续得到很多错误。我已经这样做了好几个月了,但是现在我有可以读取任意数据的 Excel 表,并且考虑到我开始使用的数据框的大小(+/- 400k),继续这种方式是不现实的。

对于数据类型“类别”和“对象(文本)”,我想用字符串“空”填充。对于 float dtypes,我想用 0.0 填充。在我的项目中,我还没有兴趣填充平均值/中值。

理想情况下,我想用一些简单的方法来实现这一点:

df.fillna_all({'float':0, 'category':'empty', 'object':'empty'})

请帮忙!

【问题讨论】:

  • 这将有助于查看示例输入和预期输出以及生成minimal reproducible example 的代码,因为您的描述并不完全清楚。也就是说,select_dtypes() 似乎适用
  • 我会编辑问题以包含您的建议,谢谢。据我了解 select_dtypes 只会选择以前被定义为特定类型的列。当我运行 df.select_dtypes(include=['float64']).columns.tolist() 时,没有返回数据,即使显然有列是浮点值。
  • 在这种情况下,请提供有关您当前如何设置 dtype 的更多信息,否则很难知道如何提供帮助。另见How to make good pandas examples

标签: python pandas


【解决方案1】:

我认为这正是您所需要的:

1) 要将categorical 变量填入“空”,您可以:

# Identify the columns in your df that are of type Object (i.e. categorical)
cat_vars = [col for col in df.columns if df[col].dtypes == 'O'] 

# Loop over them, and fill them with 'empty'
for col in df[cat_vars]:
    df[col].fillna('empty',inplace=True) 

2)要用0.0填充numerical变量,你可以这样做:

# Identify the columns that are numeric, AND have at least 1 nan to be filled
num_vars = [x for x in dat.columns if dat[x].dtypes !='O' and dat[x].isnull() > 0] 

# Loop over them, and fill them with 0.0
for col in df[num_vars]:
    df[col].fillna(0,inplace=True) 

对于未来,如果您有兴趣用 meanmedian 填充数值变量:

for col in df[num_vars]:
    df[col] = df[col].fillna(df[col].median()) # or replace with mean() for mean     

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-14
    • 1970-01-01
    • 2022-10-13
    • 2015-10-05
    • 2020-10-20
    • 1970-01-01
    • 2016-12-03
    • 1970-01-01
    相关资源
    最近更新 更多