inflearn logo
강의

Khóa học

Chia sẻ kiến thức

Chinh phục phân tích và trực quan hóa dữ liệu chỉ với hai trang tài liệu

4) Logic trong Python (và pandas) - Hiểu về các toán tử and, or, not, xor, any, all

df[df.b == 7] & df[df.a == 5] 일 때 오류가 뜹니다.

426

pyspsy12037864

3 câu hỏi đã được viết

5

df[df.b == 7] & df[df.a == 5] 를 하는데 

동영상 처럼 정상 작동이 안되고 아래와 같은 오류가 떠요 

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\ops\array_ops.py in na_logical_op(x, y, op)
    273         #  (xint or xbool) and (yint or bool)
--> 274         result = op(x, y)
    275     except TypeError:

TypeError: unsupported operand type(s) for &: 'float' and 'bool'

During handling of the above exception, another exception occurred:

TypeError                                 Traceback (most recent call last)
<ipython-input-115-a484abd3f4bf> in <module>
----> 1 df[df.b == 7] & df[df.a == 5]

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\ops\__init__.py in f(self, other, axis, level, fill_value)
    765 
    766             left, right = self.align(other, join="outer", level=level, copy=False)
--> 767             new_data = left._combine_frame(right, pass_op, fill_value)
    768             return left._construct_result(new_data)
    769 

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\frame.py in _combine_frame(self, other, func, fill_value, level)
   5298         if ops.should_series_dispatch(self, other, func):
   5299             # iterate over columns
-> 5300             new_data = ops.dispatch_to_series(self, other, _arith_op)
   5301         else:
   5302             with np.errstate(all="ignore"):

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\ops\__init__.py in dispatch_to_series(left, right, func, str_rep, axis)
    417         raise NotImplementedError(right)
    418 
--> 419     new_data = expressions.evaluate(column_op, str_rep, left, right)
    420     return new_data
    421 

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\computation\expressions.py in evaluate(op, op_str, a, b, use_numexpr)
    206     use_numexpr = use_numexpr and _bool_arith_check(op_str, a, b)
    207     if use_numexpr:
--> 208         return _evaluate(op, op_str, a, b)
    209     return _evaluate_standard(op, op_str, a, b)
    210 

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\computation\expressions.py in _evaluate_numexpr(op, op_str, a, b)
    119 
    120     if result is None:
--> 121         result = _evaluate_standard(op, op_str, a, b)
    122 
    123     return result

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\computation\expressions.py in _evaluate_standard(op, op_str, a, b)
     68         _store_test_result(False)
     69     with np.errstate(all="ignore"):
---> 70         return op(a, b)
     71 
     72 

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\ops\__init__.py in column_op(a, b)
    386 
    387         def column_op(a, b):
--> 388             return {i: func(a.iloc[:, i], b.iloc[:, i]) for i in range(len(a.columns))}
    389 
    390     elif isinstance(right, ABCSeries) and axis == "columns":

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\ops\__init__.py in <dictcomp>(.0)
    386 
    387         def column_op(a, b):
--> 388             return {i: func(a.iloc[:, i], b.iloc[:, i]) for i in range(len(a.columns))}
    389 
    390     elif isinstance(right, ABCSeries) and axis == "columns":

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\ops\common.py in new_method(self, other)
     62         other = item_from_zerodim(other)
     63 
---> 64         return method(self, other)
     65 
     66     return new_method

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\ops\__init__.py in wrapper(self, other)
    550         rvalues = extract_array(other, extract_numpy=True)
    551 
--> 552         res_values = logical_op(lvalues, rvalues, op)
    553         return _construct_result(self, res_values, index=self.index, name=res_name)
    554 

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\ops\array_ops.py in logical_op(left, right, op)
    364         filler = fill_int if is_self_int_dtype and is_other_int_dtype else fill_bool
    365 
--> 366         res_values = na_logical_op(lvalues, rvalues, op)
    367         res_values = filler(res_values)  # type: ignore
    368 

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\ops\array_ops.py in na_logical_op(x, y, op)
    279             x = ensure_object(x)
    280             y = ensure_object(y)
--> 281             result = libops.vec_binop(x, y, op)
    282         else:
    283             # let null fall thru

pandas\_libs\ops.pyx in pandas._libs.ops.vec_binop()

pandas\_libs\ops.pyx in pandas._libs.ops.vec_binop()

TypeError: unsupported operand type(s) for &: 'float' and 'bool'

pandas python

Câu trả lời 4

3

pyspsy12037864

와 제대로 되네요. 감사합니다 ^^ 

3

todaycode

안녕하세요.

질문 주신 강좌 내용의 코드 업데이트가 필요한데 늦어졌습니다.

이용에 불편을 드려 죄송해요. 아래의 코드로 실행해 보시겠어요?

df[(df.b == 7) | (df.a == 5)] 

여러개의 조건을 비교할 때는 (괄호)로 조건을 묶어서 사용합니다.

괄호로 묶어서 사용하는 이유는 &, | 연산과 연산자 우선순위로 연산 순위가 섞여서 오류가 발생할 수 있기 때문이에요.

1

xers

유툽으로 보다가 인프런 결제를 하고 오니까...안에 이런 귀한 정보가 있네요...!!

감사합니다 ㅎㅎ

0

todaycode

고맙습니다! 새해 복 많이 받으세요 :)

0

todaycode

감사합니다 :)

날짜변환 에러

0

259

0

업로드자료 오류

1

373

1

20강 관련 문의드립니다.

1

299

1

17강 도입부 실습사이트 문의

2

298

1

4강 코드 오류메세지 관련 질의

1

374

2

merge와 그룹바이 관련 질문이 있습니다.

1

494

3

쉬운 도서 추천 좀 부탁드립니다.

2

393

2

1강2강에 있는 csv파일을 다운받으면 한글이 깨져서 나와요

1

252

1

주피터노트북 목록(contents) 만들기

1

633

1

df.loc[df["거주지"].isin(gu), "지역"] = df["거주지"] 질문있습니다

1

207

1

월 주 함꼐 value_counts()

1

226

1

day_count.iloc[i]와 day_count[i]의 차이 질문

1

351

1

df 인덱싱 질문입니다

1

184

1

그래프에 한글제목을 나타내고 싶습니다.

1

535

1

배운 것 기반으로 만들어보고 있는데 질문이 있습니다.

1

404

5

질문이요

1

301

1

set_index()

1

287

1

timeit 관련 질문

1

363

1

그래프 밑에 제목을 넣으려면 어떡해야하나요???

1

421

2

한글폰트 설치 후 나오지 않는 현상 문의

1

1173

3

CSV 파일 불러오기

1

573

1

크롤링으로 csv파일 가져오기

2

320

1

영상에서 소개해주시는 웹사이트

2

260

1

질문

1

229

2