Panda Dataframe의 컬럼에서 NaN 값을 Zeroes로 대체하려면 어떻게 해야 합니까?
다음과 같은 Panda 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
수학 모듈의 .isnan을 사용하여 함수를 적용하려고 시도했습니다. 팬더 .replace 속성을 사용해 보았습니다. 팬더 0.9의 .isn 데이터 속성을 사용해 보았습니다. 함수에 NaN == NaN 문인 경우에도 시도해 보았습니다.이 기사에서는 NA 값을 R 데이터 프레임에서 0으로 치환하는 방법도 살펴보았습니다.다른 기사들을 보면서.내가 시도했던 모든 방법들이 효과가 없거나 NaN을 인식하지 못한다.힌트나 솔루션을 제공해 주시면 감사하겠습니다.
믿어요DataFrame.fillna()
이렇게 해드릴 거예요.
예:
In [7]: df
Out[7]:
0 1
0 NaN NaN
1 -0.494375 0.570994
2 NaN NaN
3 1.876360 -0.229738
4 NaN NaN
In [8]: df.fillna(0)
Out[8]:
0 1
0 0.000000 0.000000
1 -0.494375 0.570994
2 0.000000 0.000000
3 1.876360 -0.229738
4 0.000000 0.000000
NaN을 하나의 열에만 채우려면 해당 열만 선택합니다.이 경우는 inplace를 사용하고 있습니다=df의 내용을 실제로 변경할 수 있습니다.
In [12]: df[1].fillna(0, inplace=True)
Out[12]:
0 0.000000
1 0.570994
2 0.000000
3 -0.229738
4 0.000000
Name: 1
In [13]: df
Out[13]:
0 1
0 NaN 0.000000
1 -0.494375 0.570994
2 NaN 0.000000
3 1.876360 -0.229738
4 NaN 0.000000
편집:
를 피하기 위해SettingWithCopyWarning
컬럼 고유의 내장 기능을 사용합니다.
df.fillna({1:0}, inplace=True)
슬라이스를 통해 보기 또는 복사본이 반환되는 것은 보장되지 않습니다.할수있습니다
df['column'] = df['column'].fillna(value)
를 사용하여 변경할 수 있습니다.NaN
로.0
:
import pandas as pd
import numpy as np
# for column
df['column'] = df['column'].replace(np.nan, 0)
# for whole dataframe
df = df.replace(np.nan, 0)
# inplace
df.replace(np.nan, 0, inplace=True)
아래 코드가 효과가 있었습니다.
import pandas
df = pandas.read_csv('somefile.txt')
df = df.fillna(0)
아직 사람들이 많이 오는 것 같아서 업데이트/특별한 사례를 좀 알려드리고 싶었어요.다중 인덱스를 사용하는 경우 또는 인덱스 변환기를 사용하는 경우 =True 옵션은 선택한 슬라이스를 업데이트하기에 충분하지 않을 수 있습니다.예를 들어, 2x2 레벨 다중 지수에서는 이 값이 변경되지 않습니다(판다 0.15 기준).
idx = pd.IndexSlice
df.loc[idx[:,mask_1],idx[mask_2,:]].fillna(value=0,inplace=True)
문제는 체인으로 인해 원래 데이터 프레임을 갱신하는 필나 기능이 깨진다는 것입니다.특정 상황에서 이러한 체인을 통하지 않게 된 설계 결정에는 충분한 이유가 있기 때문에 인용문에 "문제"를 넣었습니다.또, 이것은 복잡한 예이지만(실제로 우연히 알게 되었지만), 슬라이스 방법에 따라서는 인덱스의 레벨이 낮아지는 경우도 있습니다.
솔루션은 DataFrame.update 입니다.
df.update(df.loc[idx[:,mask_1],idx[[mask_2],:]].fillna(value=0))
한 줄의 선으로 읽기 쉽고(어느 정도) 중간 변수나 루프를 불필요하게 방해하지 않으며 원하는 멀티 레벨 슬라이스에 필나를 적용할 수 있습니다.
이 기능이 작동하지 않는 장소를 찾을 수 있으면 댓글로 올려주세요.저는 이 문제를 만지작거리면서 소스를 보고 있습니다.그래서 적어도 제 멀티인덱스 슬라이스 문제는 해결된 것 같습니다.
사전을 사용하여 DataFrame에 있는 특정 열의 NaN 값을 채우는 대신 모든 DF를 하나의 값으로 채울 수도 있습니다.
import pandas as pd
df = pd.read_excel('example.xlsx')
df.fillna( {
'column1': 'Write your values here',
'column2': 'Write your values here',
'column3': 'Write your values here',
'column4': 'Write your values here',
.
.
.
'column-n': 'Write your values here'} , inplace=True)
결측값을 쉽게 채울 수 있는 방법:-
문자열 열 채우기: 문자열 열에 결측값 및 NaN 값이 있는 경우.
df['string column name'].fillna(df['string column name'].mode().values[0], inplace = True)
숫자 열 채우기: 숫자 열에 결측값과 NaN 값이 있는 경우.
df['numeric column name'].fillna(df['numeric column name'].mean(), inplace = True)
NaN을 0으로 채웁니다.
df['column name'].fillna(0, inplace = True)
판다의 na 값을 대체하기 위해
df['column_name'].fillna(value_to_be_replaced,inplace=True)
inplace = False
프레임를 갱신하는 값을 합니다.df(데이터 프레임)가 반환됩니다.
컬럼을 Amount
위의 표는 정수형입니다.은 다음과
df['Amount'] = df.Amount.fillna(0).astype(int)
다양한 수 .float
,str
기타 등등.
특히 같은 열의 다양한 값을 비교하기 위해 데이터형을 고려하겠습니다.
이미 많은 기고가 있었지만, 저는 이 곳에 처음 왔기 때문에, 그래도 의견을 드릴 것입니다.
두 가지 .NaN
Panda Data Frame 서을0 을을을 :
- fillna(): 함수는 지정된 방법을 사용하여 NA/NaN 값을 채웁니다.
- replace(): df.replace() 문자열, regex, 목록, 사전을 치환하기 위해 사용되는 간단한 메서드
예:
#NaN with zero on all columns
df2 = df.fillna(0)
#Using the inplace=True keyword in a pandas method changes the default behaviour.
df.fillna(0, inplace = True)
# multiple columns appraoch
df[["Student", "ID"]] = df[["Student", "ID"]].fillna(0)
마지막으로 replace() 메서드:
df["Student"] = df["Student"].replace(np.nan, 0)
다른 컬럼의 nan을 다른 방법으로 치환하려면:
replacement= {'column_A': 0, 'column_B': -999, 'column_C': -99999}
df.fillna(value=replacement)
all nan을 0으로 바꿉니다.
df = df.fillna(0)
이건 나한테는 먹히는데, 아무도 언급을 안 했어. 무슨 문제라도 있는 거야?
df.loc[df['column_name'].isnull(), 'column_name'] = 0
팬더 데이터 프레임으로 변환하는 경우, 다음을 사용하여 이 작업을 수행할 수도 있습니다.fillna
.
import numpy as np
df=np.array([[1,2,3, np.nan]])
import pandas as pd
df=pd.DataFrame(df)
df.fillna(0)
그러면 다음이 반환됩니다.
0 1 2 3
0 1.0 2.0 3.0 NaN
>>> df.fillna(0)
0 1 2 3
0 1.0 2.0 3.0 0.0
주로 두 가지 옵션을 사용할 수 있다. 결측값 NaN / np.nan의 치환 또는 채워진 경우(열 전체에 걸쳐):
df['Amount'].fillna(value=None, method= ,axis=1,)
이면 충분합니다.
매뉴얼:
value : 스칼라, dict, Series 또는 DataFrame 값(0 등), 각 인덱스(시리즈) 또는 컬럼(데이터 프레임)에 사용할 값을 지정하는 값의 dict/Series/DataFrame 값.(dict/Series/DataFrame에 없는 값은 채워지지 않습니다).이 값은 목록이 될 수 없습니다.
즉, '스트링'이나 '상수'는 더 이상 귀속될 수 없습니다.
보다 구체적인 인풋을 위해서는 SimpleImputer()를 사용합니다.
from sklearn.impute import SimpleImputer
si = SimpleImputer(strategy='constant', missing_values=np.nan, fill_value='Replacement_Value')
df[['Col-1', 'Col-2']] = si.fit_transform(X=df[['C-1', 'C-2']])
특정 컬럼에 대해 NaN을 채울 경우 loc을 사용할 수 있습니다.
d1 = {"Col1" : ['A', 'B', 'C'],
"fruits": ['Avocado', 'Banana', 'NaN']}
d1= pd.DataFrame(d1)
output:
Col1 fruits
0 A Avocado
1 B Banana
2 C NaN
d1.loc[ d1.Col1=='C', 'fruits' ] = 'Carrot'
output:
Col1 fruits
0 A Avocado
1 B Banana
2 C Carrot
Method, Axis, Limit 등 fillna()의 파라미터 구성도 언급하고 설명할 가치가 있다고 생각합니다.
문서에는 다음과 같은 내용이 기재되어 있습니다.
Series.fillna(value=None, method=None, axis=None,
inplace=False, limit=None, downcast=None)
Fill NA/NaN values using the specified method.
파라미터
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.
method [{‘backfill’, ‘bfill’, ‘pad’, ‘ffill’, None},
default None] Method to use for filling holes in
reindexed Series pad / ffill: propagate last valid
observation forward to next valid backfill / bfill:
use next valid observation to fill gap axis
[{0 or ‘index’}] Axis along which to fill missing values.
inplace [bool, default False] If True, fill
in-place. Note: this will modify any other views
on this object (e.g., a no-copy slice for a
column in a DataFrame).
limit [int,defaultNone] If method is specified,
this is the maximum number of consecutive NaN
values to forward/backward fill. In other words,
if there is a gap with more than this number of
consecutive NaNs, it will only be partially filled.
If method is not specified, this is the maximum
number of entries along the entire axis where NaNs
will be filled. Must be greater than 0 if not None.
downcast [dict, default is None] A dict of item->dtype
of what to downcast if possible, or the string ‘infer’
which will try to downcast to an appropriate equal
type (e.g. float64 to int64 if possible).
그럼 아, 럼, 럼, 저,method=
정방향 채우기(fill) 및 역방향 채우기(bfill)가 있는 매개 변수는 결측되지 않은 이전 값을 앞으로 복사합니다.
예:
import pandas as pd
import numpy as np
inp = [{'c1':10, 'c2':np.nan, 'c3':200}, {'c1':np.nan,'c2':110, 'c3':210}, {'c1':12,'c2':np.nan, 'c3':220},{'c1':12,'c2':130, 'c3':np.nan},{'c1':12,'c2':np.nan, 'c3':240}]
df = pd.DataFrame(inp)
c1 c2 c3
0 10.0 NaN 200.0
1 NaN 110.0 210.0
2 12.0 NaN 220.0
3 12.0 130.0 NaN
4 12.0 NaN 240.0
앞으로 채우기:
df.fillna(method="ffill")
c1 c2 c3
0 10.0 NaN 200.0
1 10.0 110.0 210.0
2 12.0 110.0 220.0
3 12.0 130.0 220.0
4 12.0 130.0 240.0
역방향 채우기:
df.fillna(method="bfill")
c1 c2 c3
0 10.0 110.0 200.0
1 12.0 110.0 210.0
2 12.0 130.0 220.0
3 12.0 130.0 240.0
4 12.0 NaN 240.0
Axis Parameter는 채우기 방향을 선택하는 데 도움이 됩니다.
채우기 방법:
채우기:
Axis = 1
Method = 'ffill'
----------->
direction
df.fillna(method="ffill", axis=1)
c1 c2 c3
0 10.0 10.0 200.0
1 NaN 110.0 210.0
2 12.0 12.0 220.0
3 12.0 130.0 130.0
4 12.0 12.0 240.0
Axis = 0 # by default
Method = 'ffill'
|
| # direction
|
V
e.g: # This is the ffill default
df.fillna(method="ffill", axis=0)
c1 c2 c3
0 10.0 NaN 200.0
1 10.0 110.0 210.0
2 12.0 110.0 220.0
3 12.0 130.0 220.0
4 12.0 130.0 240.0
입력:
axis= 0
method = 'bfill'
^
|
|
|
df.fillna(method="bfill", axis=0)
c1 c2 c3
0 10.0 110.0 200.0
1 12.0 110.0 210.0
2 12.0 130.0 220.0
3 12.0 130.0 240.0
4 12.0 NaN 240.0
axis = 1
method = 'bfill'
<-----------
df.fillna(method="bfill", axis=1)
c1 c2 c3
0 10.0 200.0 200.0
1 110.0 110.0 210.0
2 12.0 220.0 220.0
3 12.0 130.0 NaN
4 12.0 240.0 240.0
# alias:
# 'fill' == 'pad'
# bfill == backfill
limit 파라미터:
df
c1 c2 c3
0 10.0 NaN 200.0
1 NaN 110.0 210.0
2 12.0 NaN 220.0
3 12.0 130.0 NaN
4 12.0 NaN 240.0
첫 번째 NaN 요소만 열 전체에서 바꿉니다.
df.fillna(value = 'Unavailable', limit=1)
c1 c2 c3
0 10.0 Unavailable 200.0
1 Unavailable 110.0 210.0
2 12.0 NaN 220.0
3 12.0 130.0 Unavailable
4 12.0 NaN 240.0
df.fillna(value = 'Unavailable', limit=2)
c1 c2 c3
0 10.0 Unavailable 200.0
1 Unavailable 110.0 210.0
2 12.0 Unavailable 220.0
3 12.0 130.0 Unavailable
4 12.0 NaN 240.0
downcast 파라미터:
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5 entries, 0 to 4
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 c1 4 non-null float64
1 c2 2 non-null float64
2 c3 4 non-null float64
dtypes: float64(3)
memory usage: 248.0 bytes
df.fillna(method="ffill",downcast='infer').info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5 entries, 0 to 4
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 c1 5 non-null int64
1 c2 4 non-null float64
2 c3 5 non-null int64
dtypes: float64(1), int64(2)
memory usage: 248.0 bytes
언급URL : https://stackoverflow.com/questions/13295735/how-to-replace-nan-values-by-zeroes-in-a-column-of-a-pandas-dataframe
'programing' 카테고리의 다른 글
데이터 속성이 존재하는지 확인할 수 있는 방법이 있나요? (0) | 2022.12.31 |
---|---|
도커 컨테이너를 통한 데이터베이스 연결 문제 (0) | 2022.12.31 |
HTTP 414 "Request URI too long" 오류를 해결하려면 어떻게 해야 하나요? (0) | 2022.12.21 |
Java 문자열에서 선행 및 후행 공백 제거 (0) | 2022.12.21 |
InterfaceError(0, ') (0) | 2022.12.21 |