[Python] Dataframe 계산된 행까지만 계산하는 코드를 짜고 있어요
조회수 1829회
from pandas import Series, DataFrame
raw_data = {'': ['2018-01-01 12:00:00 AM', '2018-01-02 12:00:00 AM', '2018-01-03 12:00:00 AM', '2018-01-04 12:00:00 AM'],
'drop': [None, 1, None, None],
'collect': [None, None, None, 1]}
df = DataFrame(raw_data)
for row in df.iloc[0:df['drop'] ==True].iterrows(): #첫행부터 drop값이 존재하는 행까지에 대해 계산
if row['collect'] is True: #collect 값이 존재하면
startpoint=row[0] #그때의 시간값을 시작점에 저장
print(startpoint) #예상 결과값 : 2018-01-02 12:00:00 AM
for row in df.iloc[startpoint:df['collect'] ==True].iterrows(): #startpoint행부터 collect값이 존재하는 행까지에 대해 계산
if row['drop'] is True: #drop 값이 존재하면
startpoint=row[0] #그때의 시간값을 시작점에 저장
print(startpoint) #예상 결과값 : 2018-01-04 12:00:00 AM
df 파일에 대해서 위의 코드처럼 실행을 시키고 싶은데요. df['drop'] 열의 값이 존재하는 row에 대해서 row[0] 값을 startpoint 변수에 저장하고 싶습니다.
에러는 아래처럼 뜹니다.
Traceback (most recent call last):
File "C:/Users/serec/PycharmProjects/180929/주식+파이썬_Mr.O/질문용.py", line 8, in <module>
for row in df.iloc[0:df['drop'] ==True].iterrows(): #첫행부터 drop값이 존재하는 행까지에 대해 계산
File "C:\Anaconda3\lib\site-packages\pandas\core\indexing.py", line 1478, in __getitem__
return self._getitem_axis(maybe_callable, axis=axis)
File "C:\Anaconda3\lib\site-packages\pandas\core\indexing.py", line 2080, in _getitem_axis
return self._get_slice_axis(key, axis=axis)
File "C:\Anaconda3\lib\site-packages\pandas\core\indexing.py", line 2048, in _get_slice_axis
slice_obj = self._convert_slice_indexer(slice_obj, axis)
File "C:\Anaconda3\lib\site-packages\pandas\core\indexing.py", line 266, in _convert_slice_indexer
return ax._convert_slice_indexer(key, kind=self.name)
File "C:\Anaconda3\lib\site-packages\pandas\core\indexes\base.py", line 1706, in _convert_slice_indexer
self._validate_indexer('slice', key.stop, kind),
File "C:\Anaconda3\lib\site-packages\pandas\core\indexes\base.py", line 4145, in _validate_indexer
self._invalid_indexer(form, key)
File "C:\Anaconda3\lib\site-packages\pandas\core\indexes\base.py", line 1863, in _invalid_indexer
kind=type(key)))
TypeError: cannot do slice indexing on <class 'pandas.core.indexes.range.RangeIndex'> with these indexers [0 False
1 True
2 False
3 False
Name: drop, dtype: bool] of <class 'pandas.core.series.Series'>
Process finished with exit code 1
-
(•́ ✖ •̀)
알 수 없는 사용자
1 답변
-
dataframe에서 어떤 조건을 만족하는 첫번째 row의 index 는 다음과 같이 구할 수 있습니다.
end = df[df['drop'] == True].index[0]
따라서 첫번째 row부터 end까지 dataframe은
df.iloc[0:end+1]
처럼 가져올 수 있지요. 그러면 코드는 다음과 같이 변할거에요.
from pandas import Series, DataFrame raw_data = {'': ['2018-01-01 12:00:00 AM', '2018-01-02 12:00:00 AM', '2018-01-03 12:00:00 AM', '2018-01-04 12:00:00 AM'], 'drop': [None, 1, None, None], 'collect': [None, None, None, 1]} df = DataFrame(raw_data) end = df[df['drop'] == True].index[0] for index, row in df.iloc[0:end+1].iterrows(): #첫행부터 drop값이 존재하는 행까지에 대해 계산 if row['collect'] is True: #collect 값이 존재하면 startpoint=row[0] #그때의 시간값을 시작점에 저장 print(startpoint) #예상 결과값 : 2018-01-02 12:00:00 AM for index, row in df.iloc[0:end+1].iterrows(): #startpoint행부터 collect값이 존재하는 행까지에 대해 계산 if row['drop'] is True: #drop 값이 존재하면 startpoint=row[0] #그때의 시간값을 시작점에 저장 print(startpoint) #예상 결과값 : 2018-01-04 12:00:00 AM
댓글 입력