Pandas Dataframe对象类型Fillna异常适用于不同数据类型 [英] Pandas Dataframe object types fillna exception over different datatypes

查看:131
本文介绍了Pandas Dataframe对象类型Fillna异常适用于不同数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于不同的列,我有一个具有不同dtypes的Pandas数据框.例如. df.dtypes返回以下内容.

I have a Pandas Dataframe with different dtypes for the different columns. E.g. df.dtypes returns the following.

Date                    datetime64[ns]
FundID                           int64
FundName                        object
CumPos                           int64
MTMPrice                       float64
PricingMechanism                object

各种奶酪柱中缺少值.使用适当的NaN值对其执行组操作会导致问题.用.fillna()方法摆脱它们是显而易见的选择.问题是字符串明显是.fillna(")的clouse,而.fillna(0)是整数和浮点数的正确选择.在DataFrame上使用这两种方法都将引发异常.除了单独进行处理(大约有30列)之外,还有其他优雅的解决方案吗?我有很多代码取决于DataFrame,并且不希望不重新输入列,因为这很可能会破坏其他逻辑. 可以做:

Various of cheese columns have missing values in them. Doing a group operations on it with NaN values in place cause problems. To get rid of them with the .fillna() method is the obvious choice. Problem is the obvious clouse for strings are .fillna("") while .fillna(0) is the correct choice for ints and floats. Using either method on DataFrame throws exception. Any elegant solutions besides doing them individually (have about 30 columns)? I have a lot of code depending on the DataFrame and would prefer not to retype the columns as it is likely to break some other logic. Can do:

df.FundID.fillna(0)
df.FundName.fillna("")
etc

推荐答案

您可以遍历它们并使用if语句!

You can iterate through them and use an if statement!

for col in df:
    #get dtype for column
    dt = df[col].dtype 
    #check if it is a number
    if dt == int or dt == float:
        df[col].fillna(0)
    else:
        df[col].fillna("")

当您遍历pandas DataFrame时,将获得每个列的名称,因此使用df[col]可以访问这些列.这样,您无需手动进行操作,脚本只需遍历每一列并检查其dtype!

When you iterate through a pandas DataFrame, you will get the names of each of the columns, so to access those columns, you use df[col]. This way you don't need to do it manually and the script can just go through each column and check its dtype!

这篇关于Pandas Dataframe对象类型Fillna异常适用于不同数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆