Is there any way to get and remove last row like pop
method of python native list?
I know I can do like below. I just want to make it one line.
df.ix[df.index[-1]]
df = df[:-1]
Suppose sample dataframe:
In[51]:df
Out[51]:
a b
0 1 5
1 2 6
2 3 7
3 4 8
you can do using df.drop:
In[52]:df,last_row=df.drop(df.tail(1).index),df.tail(1)
In[53]:df
Out[53]:
0 1
0 1 5
1 2 6
2 3 7
In[54]:last_row
Out[54]:
a b
3 4 8
or using numpy as np
:
df,last_row=pd.Dataframe(np.delete(df.values,(-1),axis=0)),df.tail(1)
I tested two ways to do this: df = df[: -1] and df = df.drop(df.index[-1]). The first one is much more efficient
Here is the test with 3000 rows.
from datetime import datetime
start = datetime.now()
while df.shape[0] > 1:
df = df.drop(df.index[-1])
print(datetime.now() - start)
result: 0:00:01.558176
and, df = df.drop(df.index[-1])
from datetime import datetime
start = datetime.now()
while prices.shape[0] > 1:
prices = prices[: -1]
print(datetime.now() - start)
result: 0:00:00.337987
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With