FutureWarning: 요소별 비교 실패. 스칼라를 반환하지만 나중에 요소별 비교가 수행됩니다.
나는 판다를 사용합니다.0.19.1
Python 3 버전.이 코드 라인들에 대한 경고를 받고 있습니다.모든 행 번호가 포함된 목록을 가져오려고 합니다. 문자열Peter
에 Unnamed: 5
.
df = pd.read_excel(xls_path)
myRows = df[df['Unnamed: 5'] == 'Peter'].index.tolist()
경고가 발생합니다.
"\Python36\lib\site-packages\pandas\core\ops.py:792: FutureWarning: elementwise
comparison failed; returning scalar, but in the future will perform
elementwise comparison
result = getattr(x, name)(y)"
이 미래 경고는 무엇이며 작동하는 것 같으니 무시해야 합니다.
이 미래의 경고는 팬더가 보낸 것이 아니라 바보 같은 소리에서 나온 것입니다. 여기 문제의 근원에 가까운 경고를 재현하는 방법이 있습니다.
import numpy as np
print(np.__version__) # Numpy version '1.12.0'
'x' in np.arange(5) #Future warning thrown here
FutureWarning: elementwise comparison failed; returning scalar instead, but in the
future will perform elementwise comparison
False
이중 등호 연산자를 사용하여 이 버그를 재현하는 다른 방법:
import numpy as np
np.arange(5) == np.arange(5).astype(str) #FutureWarning thrown here
이게 무슨 일입니까?
문자열을 numpy의 숫자 유형과 비교할 때 어떤 일이 발생해야 하는지에 대해 Numpy와 네이티브 python 사이에 의견이 다릅니다.오른쪽 피연산자는 python의 영역, 원시적인 문자열, 중간 작업은 python의 영역이지만 왼쪽 피연산자는 numpy의 영역입니다.Python 스타일 스칼라를 반환해야 합니까 아니면 불리언의 Numpy 스타일 ndarray를 반환해야 합니까?Numpy는 헛소리를 늘어놓았다고 말하지만 Pythonic 개발자들은 동의하지 않습니다.전형적인 대치 상황.
배열에 항목이 있는 경우 요소별 비교 또는 스칼라여야 합니까?
가 코드또라사경중우인용가를 in
또는==
운영자들은 파이썬 문자열을 numpyndarray와 비교하기 위해 호환되지 않기 때문에, 당신이 그것을 시도하면, 그것은 스칼라를 반환하지만, 지금은 오직.경고는 앞으로 이 동작이 변경되어 python/numpy가 Numpy 스타일을 채택하기로 결정하면 코드가 카펫 전체에 토할 수 있음을 나타냅니다.
제출된 버그 보고서:
Numpy와 Python은 교착 상태에 있으며, 현재 작업은 스칼라를 반환하지만 향후에는 변경될 수 있습니다.
https://github.com/numpy/numpy/issues/6784
https://github.com/pandas-dev/pandas/issues/7830
두 가지 해결 방법:
및 되지 않을 것으로 하거나 python의 및 오른쪽 합니다.==
그리고.in
numpy 형식 또는 원시 파이썬 숫자 형식입니다.
경고를 전체적으로 억제합니다.
import warnings
import numpy as np
warnings.simplefilter(action='ignore', category=FutureWarning)
print('x' in np.arange(5)) #returns False, without Warning
경고를 한 줄씩 표시하지 않습니다.
import warnings
import numpy as np
with warnings.catch_warnings():
warnings.simplefilter(action='ignore', category=FutureWarning)
print('x' in np.arange(2)) #returns False, warning is suppressed
print('x' in np.arange(10)) #returns False, Throws FutureWarning
이름으로 경고를 억제한 다음, 이 코드가 취약하고 이러한 버전이 필요하다고 말하며 python과 numpy의 현재 버전을 언급하는 큰 댓글을 옆에 붙이면 됩니다.길 아래로 깡통을 차세요.
TLDR: pandas
제다이입니다.numpy
오막들두;그고리고.python
은하 제국입니다.
설정을 시도할 때 동일한 오류가 발생합니다.index_col
을 일읽기로 Panda
의 데이터 프레임:
df = pd.read_csv('my_file.tsv', sep='\t', header=0, index_col=['0']) ## or same with the following
df = pd.read_csv('my_file.tsv', sep='\t', header=0, index_col=[0])
저는 이런 오류를 처음 접해본 적이 없습니다.(@Eric Leschinski 설명 등을 사용하여) 저는 여전히 그 이유를 알아내려고 노력하고 있습니다.
어쨌든, 제가 그 이유를 알아낼 때까지 다음과 같은 접근법이 문제를 해결합니다.
df = pd.read_csv('my_file.tsv', sep='\t', header=0) ## not setting the index_col
df.set_index(['0'], inplace=True)
그런 행동의 이유를 파악하는 대로 업데이트하겠습니다.
을 능가할 에 아직 되지 않은 방법이. - 에릭레키놀상답랍없이수변세만지을길한아않직도언록의지은원대급되, 질빠해한에른결문방넣사있다자문목고 -열니을에합다록니습용이법친래스▁can▁that▁put문,목넣사있▁-에록다자고s'니열을▁but▁answer용▁in'습다니합ch에릭'방이▁awesome.isin
에 ==
예:
import pandas as pd
import numpy as np
df = pd.DataFrame({"Name": ["Peter", "Joe"], "Number": [1, 2]})
# Raises warning using == to compare different types:
df.loc[df["Number"] == "2", "Number"]
# No warning using .isin:
df.loc[df["Number"].isin(["2"]), "Number"]
동일한 경고 메시지에 대한 제 경험은 TypeError로 인해 발생했습니다.
유형 오류: 잘못된 유형 비교
은 데유확것좋이다습니인의 것입니다.Unnamed: 5
for x in df['Unnamed: 5']:
print(type(x)) # are they 'str' ?
다음은 경고 메시지를 복제하는 방법입니다.
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(3, 2), columns=['num1', 'num2'])
df['num3'] = 3
df.loc[df['num3'] == '3', 'num3'] = 4 # TypeError and the Warning
df.loc[df['num3'] == 3, 'num3'] = 4 # No Error
도움이 되길 바랍니다.
Eric의 답변은 문제가 Pandas Series(NumPy 배열 포함)를 Python 문자열과 비교하는 데서 발생한다는 것을 유용하게 설명합니다.불행하게도, 그의 두 가지 해결책은 모두 경고를 억제할 뿐입니다.
애초에 경고가 발생하지 않는 코드를 작성하려면 문자열을 시리즈의 각 요소와 명시적으로 비교하고 각 요소에 대해 별도의 부울을 얻습니다.예를 들어, 다음을 사용할 수 있습니다.map
그리고 익명의 기능.
myRows = df[df['Unnamed: 5'].map( lambda x: x == 'Peter' )].index.tolist()
더 간단한 방법은 시리즈의 요소가 중요한 문자열만 포함하는 단일 요소 목록에 있는지 묻는 것입니다.
myRows = df[df['Unnamed: 5'].isin( [ 'Peter' ] )].index.tolist()
은 이문에빠해방다같다습니음과법은을 입니다.numpy.core.defchararray
저도 같은 경고 메시지에 직면했고 위 모듈을 사용하여 해결할 수 있었습니다.
import numpy.core.defchararray as npd
resultdataset = npd.equal(dataset1, dataset2)
어레이가 너무 크지 않거나 어레이 수가 너무 많지 않은 경우에는 스토리지의 왼쪽 부분을 강제로 사용하지 않아도 됩니다.==
문자열이 될 경우:
myRows = df[str(df['Unnamed: 5']) == 'Peter'].index.tolist()
하지만 이 속도는 다음과 같은 경우 최대 1.5배 느립니다.df['Unnamed: 5']
0인 경우 . 25-30인 경우에는 0.25-30배 느립니다.df['Unnamed: 5']
는 작은 numpy 배열(길이 = 10)이며, 길이가 100인 numpy 배열일 경우 150-160배 느립니다(평균 500회 이상 시행).
a = linspace(0, 5, 10)
b = linspace(0, 50, 100)
n = 500
string1 = 'Peter'
string2 = 'blargh'
times_a = zeros(n)
times_str_a = zeros(n)
times_s = zeros(n)
times_str_s = zeros(n)
times_b = zeros(n)
times_str_b = zeros(n)
for i in range(n):
t0 = time.time()
tmp1 = a == string1
t1 = time.time()
tmp2 = str(a) == string1
t2 = time.time()
tmp3 = string2 == string1
t3 = time.time()
tmp4 = str(string2) == string1
t4 = time.time()
tmp5 = b == string1
t5 = time.time()
tmp6 = str(b) == string1
t6 = time.time()
times_a[i] = t1 - t0
times_str_a[i] = t2 - t1
times_s[i] = t3 - t2
times_str_s[i] = t4 - t3
times_b[i] = t5 - t4
times_str_b[i] = t6 - t5
print('Small array:')
print('Time to compare without str conversion: {} s. With str conversion: {} s'.format(mean(times_a), mean(times_str_a)))
print('Ratio of time with/without string conversion: {}'.format(mean(times_str_a)/mean(times_a)))
print('\nBig array')
print('Time to compare without str conversion: {} s. With str conversion: {} s'.format(mean(times_b), mean(times_str_b)))
print(mean(times_str_b)/mean(times_b))
print('\nString')
print('Time to compare without str conversion: {} s. With str conversion: {} s'.format(mean(times_s), mean(times_str_s)))
print('Ratio of time with/without string conversion: {}'.format(mean(times_str_s)/mean(times_s)))
결과:
Small array:
Time to compare without str conversion: 6.58464431763e-06 s. With str conversion: 0.000173756599426 s
Ratio of time with/without string conversion: 26.3881526541
Big array
Time to compare without str conversion: 5.44309616089e-06 s. With str conversion: 0.000870866775513 s
159.99474375821288
String
Time to compare without str conversion: 5.89370727539e-07 s. With str conversion: 8.30173492432e-07 s
Ratio of time with/without string conversion: 1.40857605178
저는 이것을 하기 위해 가능한 몇 가지 방법을 비교해 보았습니다. 판다, 몇 가지 멍한 방법, 그리고 목록 이해 방법을 포함합니다.
먼저 기준부터 살펴보겠습니다.
>>> import numpy as np
>>> import operator
>>> import pandas as pd
>>> x = [1, 2, 1, 2]
>>> %time count = np.sum(np.equal(1, x))
>>> print("Count {} using numpy equal with ints".format(count))
CPU times: user 52 µs, sys: 0 ns, total: 52 µs
Wall time: 56 µs
Count 2 using numpy equal with ints
그래서, 우리의 기준은 숫자가 정확해야 한다는 것입니다.2
그리고 우리는 약을 취해야 합니다.50 us
.
이제 우리는 순진한 방법을 시도합니다.
>>> x = ['s', 'b', 's', 'b']
>>> %time count = np.sum(np.equal('s', x))
>>> print("Count {} using numpy equal".format(count))
CPU times: user 145 µs, sys: 24 µs, total: 169 µs
Wall time: 158 µs
Count NotImplemented using numpy equal
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/ipykernel_launcher.py:1: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
"""Entry point for launching an IPython kernel.
그리고 여기서, 우리는 틀린 답을 얻습니다.NotImplemented != 2
), 시간이 오래 걸리고 경고를 던집니다.
그래서 우리는 다른 순진한 방법을 시도할 것입니다.
>>> %time count = np.sum(x == 's')
>>> print("Count {} using ==".format(count))
CPU times: user 46 µs, sys: 1 µs, total: 47 µs
Wall time: 50.1 µs
Count 0 using ==
다시 오답 (0 != 2
). 이후의 경고()가 없기 때문에 더욱 음흉합니다.0
와 같이 전달될 수 있습니다.2
).
이제 목록 이해를 시도해 보겠습니다.
>>> %time count = np.sum([operator.eq(_x, 's') for _x in x])
>>> print("Count {} using list comprehension".format(count))
CPU times: user 55 µs, sys: 1 µs, total: 56 µs
Wall time: 60.3 µs
Count 2 using list comprehension
우리는 여기서 정답을 맞았고, 그것은 꽤 빠릅니다!
다른 가능성, 또다가성은능른▁another,.pandas
:
>>> y = pd.Series(x)
>>> %time count = np.sum(y == 's')
>>> print("Count {} using pandas ==".format(count))
CPU times: user 453 µs, sys: 31 µs, total: 484 µs
Wall time: 463 µs
Count 2 using pandas ==
느리지만 정확합니다!
제가입니다.numpy
을 배열합니다.object
예:예:
>>> x = np.array(['s', 'b', 's', 'b']).astype(object)
>>> %time count = np.sum(np.equal('s', x))
>>> print("Count {} using numpy equal".format(count))
CPU times: user 50 µs, sys: 1 µs, total: 51 µs
Wall time: 55.1 µs
Count 2 using numpy equal
빠르고 정확하게!
저의 경우, 시리즈가 np.nan만 있었기 때문에 일반적인 유형의 부울 인덱스 때문에 경고가 발생했습니다.시연(판다 1.0.3):
>>> import pandas as pd
>>> import numpy as np
>>> pd.Series([np.nan, 'Hi']) == 'Hi'
0 False
1 True
>>> pd.Series([np.nan, np.nan]) == 'Hi'
~/anaconda3/envs/ms3/lib/python3.7/site-packages/pandas/core/ops/array_ops.py:255: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
res_values = method(rvalues)
0 False
1 False
판다 1.0과 함께 그들은 당신이 정말로 새로운 것을 사용하기를 원한다고 생각합니다.'string'
이터유형을 하는 데이터 :pd.NA
값:
>>> pd.Series([pd.NA, pd.NA]) == 'Hi'
0 False
1 False
>>> pd.Series([np.nan, np.nan], dtype='string') == 'Hi'
0 <NA>
1 <NA>
>>> (pd.Series([np.nan, np.nan], dtype='string') == 'Hi').fillna(False)
0 False
1 False
부울 인덱싱과 같은 일상적인 기능을 사용하는 시점을 좋아하지 않습니다.
제 컬럼에 null 문자열이 포함되어 있는 줄 알고 이 경고를 받았는데, 확인해보니 np.nan이 포함되어 있었습니다!
if df['column'] == '':
내 칼럼을 빈 문자열로 바꾸는 것이 도움이 되었습니다 :)
오류의 원인이 되는 코드가 있습니다.
for t in dfObj['time']:
if type(t) == str:
the_date = dateutil.parser.parse(t)
loc_dt_int = int(the_date.timestamp())
dfObj.loc[t == dfObj.time, 'time'] = loc_dt_int
다음과 같이 변경했습니다.
for t in dfObj['time']:
try:
the_date = dateutil.parser.parse(t)
loc_dt_int = int(the_date.timestamp())
dfObj.loc[t == dfObj.time, 'time'] = loc_dt_int
except Exception as e:
print(e)
continue
위에서 언급한 바와 같이 경고를 던지는 비교를 방지합니다.나는 단지 예외를 피하기만 하면 되었습니다.dfObj.loc
for 루프에는 이미 변경된 행을 확인하지 말라는 방법이 있을 수 있습니다.
제 경험상, 저는 'numpy.ndarray'와 "(빈 문자열)를 비교하고 있었습니다.
if( (self.images[0] != "" ):
# Also didn't work.
if( (self.images[0].astype(str) != "" ):
이를 해결하기 위해 길이를 0과 비교해보니 경고가 사라졌습니다.
if( len(self.images[0]) != 0 ):
언급URL : https://stackoverflow.com/questions/40659212/futurewarning-elementwise-comparison-failed-returning-scalar-but-in-the-futur
'programing' 카테고리의 다른 글
SQL - 서버의 IP 주소를 가져오는 쿼리 (0) | 2023.05.20 |
---|---|
각 카테고리별 상위 10개 레코드 선택 (0) | 2023.05.20 |
파이썬을 사용하여 Excel 문서 구문 분석 (0) | 2023.05.20 |
VB.NET 코드를 C#로 마이그레이션할 때 for 루프가 다르게 작동하는 이유는 무엇입니까? (0) | 2023.05.20 |
C#에서 복싱과 언복싱이 필요한 이유는 무엇입니까? (0) | 2023.05.20 |