Get last value of each columns in Pandas Dataframe

From this question, I know how to get the last value of a column. But I want a list/series of all the last values of every columns. Easy way is to iterate over each columns and do something like this -

df = pd.DataFrame(np.random.randn(10,5), columns = ['a','b','c','d','e'])
l = []
for col in df.columns.values:
    l.append(df[col].iloc[-1])

But I am looking for more pythonic way.

Upvotes: 3

Views: 1355

Answers (4)

Allen Qin
Allen Qin

Reputation: 19957

If you want a list:

df.iloc[-1].tolist()

Upvotes: 1

mozway
mozway

Reputation: 262284

Simply use tail on the whole frame:

df.tail(1)

Or to get a Series use iloc:

df.iloc[-1]

Upvotes: 1

jezrael
jezrael

Reputation: 863531

Use DataFrame.iloc for select last row:

print (df.iloc[-1])

If need list:

print (df.iloc[-1].tolist())

Sample:

np.random.seed(2021)
df = pd.DataFrame(np.random.randn(10,5), columns = ['a','b','c','d','e'])
print (df)

l = []
for col in df.columns.values:
    l.append(df[col].iloc[-1])
print (l)
[1.2242357215843627, -0.5456577180464415, 0.9067480525839758, -0.9826172361069304, -0.6331618916225082]

print (df.iloc[-1].tolist())
[1.2242357215843627, -0.5456577180464415, 0.9067480525839758, -0.9826172361069304, -0.6331618916225082]

Upvotes: 2

ql.user2511
ql.user2511

Reputation: 389

Try this code line please:

df.iloc[-1]

Upvotes: 1

Related Questions