programing

Python/NumPy 목록에서 Nan을 제거하는 방법

bestprogram 2023. 7. 16. 13:43

Python/NumPy 목록에서 Nan을 제거하는 방법

값이 포함된 목록이 있는데, 받은 값 중 하나는 'nan'입니다.

countries= [nan, 'USA', 'UK', 'France']

제거하려고 했지만 매번 오류가 발생합니다.

cleanedList = [x for x in countries if (math.isnan(x) == True)]
TypeError: a float is required

내가 이걸 시도했을 때:

cleanedList = cities[np.logical_not(np.isnan(countries))]
cleanedList = cities[~np.isnan(countries)]

TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

질문도 바뀌었고, 답도 바뀌었습니다.

다음을 사용하여 문자열을 테스트할 수 없습니다.math.isnan이것은 부동 인수를 예상하기 때문입니다.당신의countries목록, 당신은 부유물과 끈을 가지고 있습니다.

귀하의 경우 다음 사항으로 충분합니다.

cleanedList = [x for x in countries if str(x) != 'nan']

구답

당신의countries리스트, 리터럴'nan'Python float이 아닌 문자열입니다.nan이 값은 다음과 같습니다.

float('NaN')

귀하의 경우 다음 사항으로 충분합니다.

cleanedList = [x for x in countries if x != 'nan']

예를 들어...

countries= [nan, 'USA', 'UK', 'France']

난은 난과 같지 않기 때문에 (nan != nan) 및countries[0] = nan다음 사항을 준수해야 합니다.

countries[0] == countries[0]
False

하지만,

countries[1] == countries[1]
True
countries[2] == countries[2]
True
countries[3] == countries[3]
True

따라서 다음과 같이 작동해야 합니다.

cleanedList = [x for x in countries if x == x]

문제는 이 사실에서 비롯됩니다.np.isnan()문자열 값을 올바르게 처리하지 않습니다.예를 들어 다음과 같은 작업을 수행할 수 있습니다.

np.isnan("A")
TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

하지만 판다 버전은pd.isnull()숫자 및 문자열 값에 대해 작동합니다.

import pandas as pd
pd.isnull("A")
> False

pd.isnull(3)
> False

pd.isnull(np.nan)
> True

pd.isnull(None)
> True
import numpy as np

mylist = [3, 4, 5, np.nan]
l = [x for x in mylist if ~np.isnan(x)]

이렇게 하면 모든 NaN이 제거됩니다.물론 여기서는 문자열이 아니라 실제 NaN(np.nan).

다음과 같은 목록에서 결측값을 제거하고 싶습니다.

import pandas as pd
list_no_nan = [x for x in list_with_nan if pd.notnull(x)]

numpy 팬시 인덱싱 사용:

In [29]: countries=np.asarray(countries)

In [30]: countries[countries!='nan']
Out[30]: 
array(['USA', 'UK', 'France'], 
      dtype='|S6')

요소 유형을 확인하는 경우

type(countries[1])

결과는 다음과 같습니다.<class float>다음 코드를 사용할 수 있습니다.

[i for i in countries if type(i) is not float]

nan 값을 직접 제거하는 방법은 다음과 같습니다.

import numpy as np    
countries.remove(np.nan)

다른 방법으로는 다음과 같은 필터를 사용하는 것이 있습니다.

countries = list(filter(lambda x: str(x) != 'nan', countries))

예를 들어,'nan'를 사용하는 대신 문자열입니다.isnan()그냥 문자열을 확인합니다.

다음과 같이:

cleanedList = [x for x in countries if x != 'nan']

제 생각에는 제안된 솔루션의 대부분이 성능을 고려하지 않은 것 같습니다.목록에 많은 값이 있는 경우 및 목록 이해 루프는 유효한 솔루션이 아닙니다.아래 솔루션은 계산 시간 측면에서 더 효율적이며 목록에 숫자나 문자열이 있다고 가정하지 않습니다.

import numpy as np
import pandas as pd
list_var = [np.nan, 4, np.nan, 20,3, 'test']
df = pd.DataFrame({'list_values':list_var})
list_var2 = list(df['list_values'].dropna())
print("\n* list_var2 = {}".format(list_var2))

서로 다른 유형의 항목 목록이 있고 NaN을 필터링하려면 다음을 수행할 수 있습니다.

import math
lst = [1.1, 2, 'string', float('nan'), {'di':'ct'}, {'set'}, (3, 4), ['li', 5]]
filtered_lst = [x for x in lst if not (isinstance(x, float) and math.isnan(x))]

출력:

[1.1, 2, 'string', {'di': 'ct'}, {'set'}, (3, 4), ['li', 5]]

범위 목록에서 0 제외

['ret'+str(x) for x in list(range(-120,241,5)) if (x!=0) ]

예를 들어 판다가 빈 값으로 '난'을 반환한다는 것을 알게 되었습니다.문자열이 아니므로 문자열로 변환해야 일치합니다.예:

ulist = df.column1.unique() #create a list from a column with Pandas which 
for loc in ulist:
    loc = str(loc)   #here 'nan' is converted to a string to compare with if
    if loc != 'nan':
        print(loc)
import numpy as np
countries=[x for x in countries if x is not np.nan]

언급URL : https://stackoverflow.com/questions/21011777/how-can-i-remove-nan-from-list-python-numpy