반응형

08. 판다스 데이터프레임(Pandas DataFrame) 범위 데이터 사용하기

1) 기본 코드

import pandas as pd

data = [['B00232', '새우깡', '2022-11-01', 1600],
         ['B03215', '양파링', '2023-01-31', 1200],
         ['B12098', '계란과자', '2022-06-03', 1400]]
columns = ['바코드', '제품명', '유통기한', '판매가']

df = pd.DataFrame(data=data, columns=columns)

df = df.set_index('바코드')

print(df)

 

반응형

 

2) 실행 결과

fdf = df['판매가'] > 1500
print(fdf)
print(df[fdf])
바코드
B00232     True
B03215    False
B12098    False
Name: 판매가, dtype: bool

        제품명        유통기한   판매가
바코드                          
B00232  새우깡  2022-11-01  1600
  • df에서 판매가가 1500인 행 찾기
  • print(df[fdf])로 해당 데이터만 출력
fdf2 = df.iloc[0:2]['판매가'] > 1500
print(fdf2)
print(df[fdf2])
바코드
B00232     True
B03215    False
Name: 판매가, dtype: bool


C:\Users\Lee\AppData\Local\Temp\ipykernel_11352\1377462347.py:3: UserWarning: Boolean Series key will be reindexed to match DataFrame index.
  print(df[fdf2])



---------------------------------------------------------------------------

IndexingError                             Traceback (most recent call last)

Input In [11], in <module>
      1 fdf2 = df.iloc[0:2]['판매가'] > 1500
      2 print(fdf2)
----> 3 print(df[fdf2])


File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\frame.py:3497, in DataFrame.__getitem__(self, key)
   3495 # Do we have a (boolean) 1d indexer?
   3496 if com.is_bool_indexer(key):
-> 3497     return self._getitem_bool_array(key)
   3499 # We are left with two options: a single key, and a collection of keys,
   3500 # We interpret tuples as collections only for non-MultiIndex
   3501 is_single_key = isinstance(key, tuple) or not is_list_like(key)


File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\frame.py:3550, in DataFrame._getitem_bool_array(self, key)
   3544     raise ValueError(
   3545         f"Item wrong length {len(key)} instead of {len(self.index)}."
   3546     )
   3548 # check_bool_indexer will throw exception if Series key cannot
   3549 # be reindexed to match DataFrame rows
-> 3550 key = check_bool_indexer(self.index, key)
   3551 indexer = key.nonzero()[0]
   3552 return self._take_with_is_copy(indexer, axis=0)


File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\indexing.py:2375, in check_bool_indexer(index, key)
   2373     mask = isna(result._values)
   2374     if mask.any():
-> 2375         raise IndexingError(
   2376             "Unalignable boolean Series provided as "
   2377             "indexer (index of the boolean Series and of "
   2378             "the indexed object do not match)."
   2379         )
   2380     return result.astype(bool)._values
   2381 if is_object_dtype(key):
   2382     # key might be object-dtype bool, check_array_indexer needs bool array


IndexingError: Unalignable boolean Series provided as indexer (index of the boolean Series and of the indexed object do not match).
  • df는 3행이고 fdf는 2행이므로 서로 행수가 맞지 않아 에러 발생
  • df.iloc[0:1]을 이용하여 같은 2행으로 행수를 맞춰줘야 아래처럼 이상없이 실행 가능
print(df.iloc[0:1][fdf])
        제품명        유통기한   판매가
바코드                          
B00232  새우깡  2022-11-01  1600
반응형

+ Recent posts