如何替换数据帧列中的NAN值
我有一个pandas dataframe如下:
itm Date Amount
67 420 2012-09-30 00:00:00 65211
68 421 2012-09-09 00:00:00 29424
69 421 2012-09-16 00:00:00 29877
70 421 2012-09-23 00:00:00 30990
71 421 2012-09-30 00:00:00 61303
72 485 2012-09-09 00:00:00 71781
73 485 2012-09-16 00:00:00 NaN
74 485 2012-09-23 00:00:00 11072
75 485 2012-09-30 00:00:00 113702
76 489 2012-09-09 00:00:00 64731
77 489 2012-09-16 00:00:00 NaN
当我尝试将函数应用于金额列时,我会收到以下错误:
ValueError: cannot convert float NaN to integer
我尝试使用Math.isnan
,pandas'应用函数。替换
方法,.sparse
pandas 0.9的数据属性,如果nan == nan == nan
语句在函数中;我还研究了 this q/a ;他们都没有工作。
我该怎么做?
I have a Pandas Dataframe as below:
itm Date Amount
67 420 2012-09-30 00:00:00 65211
68 421 2012-09-09 00:00:00 29424
69 421 2012-09-16 00:00:00 29877
70 421 2012-09-23 00:00:00 30990
71 421 2012-09-30 00:00:00 61303
72 485 2012-09-09 00:00:00 71781
73 485 2012-09-16 00:00:00 NaN
74 485 2012-09-23 00:00:00 11072
75 485 2012-09-30 00:00:00 113702
76 489 2012-09-09 00:00:00 64731
77 489 2012-09-16 00:00:00 NaN
When I try to apply a function to the Amount column, I get the following error:
ValueError: cannot convert float NaN to integer
I have tried applying a function using math.isnan
, pandas' .replace
method, .sparse
data attribute from pandas 0.9, if NaN == NaN
statement in a function; I have also looked at this Q/A; none of them works.
How do I do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(16)
noreferrer“>
dataframe.fillna()
或
系列。 fillna()
将为您执行此操作。示例:
要仅在一个列中填充NAN,请仅选择该列。
或者,您可以使用内置的特定功能:
DataFrame.fillna()
orSeries.fillna()
will do this for you.Example:
To fill the NaNs in only one column, select just that column.
Or you can use the built in column-specific functionality:
不能保证切片返回视图或副本。你可以做
It is not guaranteed that the slicing returns a view or a copy. You can do
您可以使用将
NAN
更改为0
:You could use
replace
to changeNaN
to0
:以下代码对我有用。
The below code worked for me.
我只是想提供一个特殊情况。如果您使用的是多指数或以其他方式使用索引 - 缝线,则
inplace = true
选项可能不足以更新您选择的切片。例如,在2x2级的多指数中,这不会更改任何值(从PANDAS 0.15开始):“问题”是链接破坏了更新原始数据框的FillNA的能力。我将“问题”放在引号中,因为设计决策的理由有很多,导致在某些情况下不会通过这些链条进行解释。另外,这是一个复杂的示例(尽管我真的遇到了它),但是根据您的切片方式,相同的索引级别也可能更少。
The solution is
DataFrame.update
< /a>:这是一行,读得很好(有点),并消除了与中间变量或循环的任何不必要的混乱,同时允许您将fillna应用于您喜欢的任何多级切片!
如果有人能找到该位置不起作用,请在评论中发布,我一直在弄乱它并查看来源,它似乎至少解决了我的多索引切片问题。
I just wanted to provide a special case. If you're using a multi-index or otherwise using an index-slicer, the
inplace=True
option may not be enough to update the slice you've chosen. For example in a 2x2 level multi-index this will not change any values (as of pandas 0.15):The "problem" is that the chaining breaks the fillna ability to update the original dataframe. I put "problem" in quotes because there are good reasons for the design decisions that led to not interpreting through these chains in certain situations. Also, this is a complex example (though I really ran into it), but the same may apply to fewer levels of indexes depending on how you slice.
The solution is
DataFrame.update
:It's one line, reads reasonably well (sort of) and eliminates any unnecessary messing with intermediate variables or loops while allowing you to apply fillna to any multi-level slice you like!
If anybody can find places this doesn't work please post in the comments, I've been messing with it and looking at the source and it seems to solve at least my multi-index slice problems.
您还可以使用字典来填充数据框中特定列的NAN值,而不是用一些OneValue填充所有DF。
You can also use dictionaries to fill NaN values of the specific columns in the DataFrame rather to fill all the DF with some oneValue.
填充缺失值的简便方法: -
填充 字符串列:当字符串列缺少值和NAN值时。
填充 数字列:当数字列缺少值和NAN值时。
用零填充南:
Easy way to fill the missing values:-
filling string columns: when string columns have missing values and NaN values.
filling numeric columns: when the numeric columns have missing values and NaN values.
filling NaN with zero:
如果
Inplace = false
,请替换熊猫中的Na值,而不是更新DF(DataFrame),它将返回修改后的值。
To replace na values in pandas
if
inplace=False
, instead of updating the df (dataframe) it will return the modified values.考虑到上表中的特定列
量
是整数类型,以下是一个解决方案:类似地,您可以用
float
,str 等等。
特别是,我将考虑数据类型比较同一列的各种值。
Considering the particular column
Amount
in the above table is of integer type, the following would be a solution:Similarly, you can fill it with various data types like
float
,str
and so on.In particular, I would consider datatype to compare various values of the same column.
以不同的方式替换不同列的NAN:
To replace nan in different columns with different ways:
这对我有用,但没有人提到。有什么问题吗?
This works for me, but no one's mentioned it. could there be something wrong with it?
主要有两种选择。如果插补或填充缺失值 nan / np.nan < / em>仅具有数值替换(跨列(s):
df ['MANTER']。fillna(value = none,method = none,method = = ,轴= 1,)
足够:从文档:
值:标量,dict,series或dataframe
用于填充孔的价值(例如0),或者
dict/series/series/dataframe值的值指定要使用的值
每个索引(用于系列)或列(对于数据框)。 (值不
在dict/series/dataframe中,将不填充)。这个值不能
成为列表。
这意味着不再允许“弦”或“常数”推出。
有关更专业的归档,请使用 > :
There are two options available primarily; in case of imputation or filling of missing values NaN / np.nan with only numerical replacements (across column(s):
df['Amount'].fillna(value=None, method= ,axis=1,)
is sufficient:From the Documentation:
value : scalar, dict, Series, or DataFrame
Value to use to fill holes (e.g. 0), alternately a
dict/Series/DataFrame of values specifying which value to use for
each index (for a Series) or column (for a DataFrame). (values not
in the dict/Series/DataFrame will not be filled). This value cannot
be a list.
Which means 'strings' or 'constants' are no longer permissable to be imputed.
For more specialized imputations use SimpleImputer():
如果要填充NAN的特定列,则可以使用LOC:
输出:
输出:
If you want to fill NaN for a specific column you can use loc:
output:
output:
我认为这也值得一提和解释
fillna()的参数配置
类似于方法,轴,限制等。
从文档中,我们拥有:
参数
确定。让我们从
method =
参数开始具有前向填充(FFILL)和向后填充(BFILL)
ffill正在对以前的复制进行复制
非缺失值。
例如:
前向填充:
向后填充:
轴参数可帮助我们选择填充方向:
填充方向:
ffill:
bfill: bfill:
limit参数:
仅跨列替换第一个NAN元素:
Downcast参数:
I think it's also worth mention and explain
the parameters configuration of fillna()
like Method, Axis, Limit, etc.
From the documentation we have:
Parameters
Ok. Let's start with the
method=
Parameter thishave forward fill (ffill) and backward fill(bfill)
ffill is doing copying forward the previous
non missing value.
e.g. :
Forward fill:
Backward fill:
The Axis Parameter help us to choose the direction of the fill:
Fill directions:
ffill:
bfill:
limit parameter:
Only replace the first NaN element across columns:
downcast parameter:
如果您使用
read_csv
等读取具有缺少值的数据,则可以将keep_default_na = false
读取为空字符串(>“ “
)。在特定情况下,这很有用,因为它可以在一个函数呼叫中实现fillna
fillna 替换的功能(在内存中少一个复制)。如果数据帧包含数字,则可以将DTYPE传递到
read_csv
以使用所需的DTYPE列构造数据框。替换NAN的另一种方法是通过
mask()
/其中()
方法。它们是类似的方法,其中mask
替换满足条件的值,而 代替不满足条件的值。因此,要使用,我们只需要过滤NAN值并将其替换为所需值。这种方法的优点是我们可以将其有条件地用它替换NAN值。以下是一个示例,其中
df
中的NAN值被10
代替,如果条件cond> cond
得到满足。在引擎盖下,
fillna()
调用其中()
( source ),又呼叫numpy.where()
(如果数据帧很小,并且numexpr) 。 “>来源)。因此,
fillna
/mask
/其中
在更换NAN值的目的基本上是相同的方法。另一方面,替换()
(此页面上给出的另一种方法)是numpy.putmask
操作( source source )。因为numexpr
比numpy
对于大型数组而言,numpy
,对于非常大的数据范围,替换>替换
的表现可能超过其他方法。从切线上说,数据框中具有文字字符串
'nan'
而不是实际的NAN值是常见的。为确保数据框确实具有NAN值,请使用df.isna()。任何()
检查。如果它返回false,则在包含NAN时,您可能会有'NAN'
字符串,在这种情况下,请使用replast
将它们转换为NAN或更好,甚至更好,甚至更好替换为要替换为替换的价值。例如:If you're reading data with missing values from a file using
read_csv
etc., then you can passkeep_default_na=False
to read missing values as empty strings (""
). In specific cases, this is useful because it achieves whatfillna
orreplace
does in one function call (with one less copy in memory).If the dataframe contains numbers, then you can pass dtypes to
read_csv
to construct a dataframe with the desired dtype columns.Another way to replace NaN is via
mask()
/where()
methods. They are similar methods wheremask
replaces values that satisfy the condition whereaswhere
replaces values that do not satisfy the condition. So to use, we just have to filter the NaN values and replace them with the desired value.The advantage of this method is that we can conditionally replace NaN values with it. The following is an example where NaN values in
df
are replaced by10
if the conditioncond
is satisfied.Under the hood,
fillna()
callswhere()
(source) which in turn callsnumpy.where()
if the dataframe is small andnumexpr.evaluate
if it's large (source). Sofillna
/mask
/where
are essentially the same method for the purposes of replacing NaN values. On the other hand,replace()
(another method given on this page) is anumpy.putmask
operation (source). Becausenumexpr
is a faster thannumpy
for large arrays, for very large dataframes,replace
may be outperformed by the other methods.On a tangential note, it's common for a dataframe to have a literal string
'NaN'
instead of an actual NaN value. To make sure that a dataframe indeed has NaN values, check withdf.isna().any()
. If it returns False, when it should contain NaN, then you probably have'NaN'
strings, in which case, usereplace
to convert them into NaN or, even better, replace with the value you're meant to replace it with. For example:使用 lambda 表达式,也可以用0代替NAN。
以下是一个示例:
Using lambda expression, it is also possible to replace NaN with 0.
Below is an example: