IT TIP

Pandas 데이터 프레임의 마지막 데이터 행을 삭제하는 방법

itqueen 2020. 11. 25. 21:48
반응형

Pandas 데이터 프레임의 마지막 데이터 행을 삭제하는 방법


나는 이것이 간단해야한다고 생각하지만 몇 가지 아이디어를 시도했지만 그중 어느 것도 작동하지 않았습니다.

last_row = len(DF)
DF = DF.drop(DF.index[last_row])  #<-- fail!

음수 인덱스를 사용해 보았지만 오류가 발생했습니다. 나는 여전히 기본적인 것을 오해하고있을 것입니다.

미리 감사드립니다.


마지막 n 개 행을 삭제하려면 :

df.drop(df.tail(n).index,inplace=True) # drop last n rows

같은 맥락에서 처음 n 개 행을 삭제할 수 있습니다.

df.drop(df.head(n).index,inplace=True) # drop first n rows

Python의 인덱스 위치 지정은 0부터 시작하기 때문에 실제로에 index해당하는 위치에 요소가 없습니다 len(DF). 당신은 그것이 필요합니다 last_row = len(DF) - 1:

In [49]: dfrm
Out[49]: 
          A         B         C
0  0.120064  0.785538  0.465853
1  0.431655  0.436866  0.640136
2  0.445904  0.311565  0.934073
3  0.981609  0.695210  0.911697
4  0.008632  0.629269  0.226454
5  0.577577  0.467475  0.510031
6  0.580909  0.232846  0.271254
7  0.696596  0.362825  0.556433
8  0.738912  0.932779  0.029723
9  0.834706  0.002989  0.333436

[10 rows x 3 columns]

In [50]: dfrm.drop(dfrm.index[len(dfrm)-1])
Out[50]: 
          A         B         C
0  0.120064  0.785538  0.465853
1  0.431655  0.436866  0.640136
2  0.445904  0.311565  0.934073
3  0.981609  0.695210  0.911697
4  0.008632  0.629269  0.226454
5  0.577577  0.467475  0.510031
6  0.580909  0.232846  0.271254
7  0.696596  0.362825  0.556433
8  0.738912  0.932779  0.029723

[9 rows x 3 columns]

그러나 작성하는 것이 훨씬 간단합니다 DF[:-1].


DF[:-n]

여기서 n은 삭제할 마지막 행 수입니다.

마지막 행을 삭제하려면 :

DF = DF[:-1]

stats = pd.read_csv("C:\\py\\programs\\second pandas\\ex.csv")

통계 결과 :

       A            B          C
0   0.120064    0.785538    0.465853
1   0.431655    0.436866    0.640136
2   0.445904    0.311565    0.934073
3   0.981609    0.695210    0.911697
4   0.008632    0.629269    0.226454
5   0.577577    0.467475    0.510031
6   0.580909    0.232846    0.271254
7   0.696596    0.362825    0.556433
8   0.738912    0.932779    0.029723
9   0.834706    0.002989    0.333436

그냥 사용 skipfooter=1

skipfooter : int, 기본값 0

건너 뛸 파일 하단의 줄 수

stats_2 = pd.read_csv("C:\\py\\programs\\second pandas\\ex.csv", skipfooter=1, engine='python')

stats_2의 출력

       A          B            C
0   0.120064    0.785538    0.465853
1   0.431655    0.436866    0.640136
2   0.445904    0.311565    0.934073
3   0.981609    0.695210    0.911697
4   0.008632    0.629269    0.226454
5   0.577577    0.467475    0.510031
6   0.580909    0.232846    0.271254
7   0.696596    0.362825    0.556433
8   0.738912    0.932779    0.029723

drop returns a new array so that is why it choked in the og post; I had a similar requirement to rename some column headers and deleted some rows due to an ill formed csv file converted to Dataframe, so after reading this post I used:

newList = pd.DataFrame(newList)
newList.columns = ['Area', 'Price']
print(newList)
# newList = newList.drop(0)
# newList = newList.drop(len(newList))
newList = newList[1:-1]
print(newList)

and it worked great, as you can see with the two commented out lines above I tried the drop.() method and it work but not as kool and readable as using [n:-n], hope that helps someone, thanks.


Surprised nobody brought this one up:

# To remove last n rows
df.head(-n)

# To remove first n rows
df.tail(-n)

Running a speed test on a DataFrame of 1000 rows shows that slicing and head/tail are ~6 times faster than using drop:

>>> %timeit df[:-1]
125 µs ± 132 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

>>> %timeit df.head(-1)
129 µs ± 1.18 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

>>> %timeit df.drop(df.tail(1).index)
751 µs ± 20.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

참고URL : https://stackoverflow.com/questions/26921651/how-to-delete-the-last-row-of-data-of-a-pandas-dataframe

반응형