3

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.

4 Answers 4

2

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]
Sign up to request clarification or add additional context in comments.

Comments

1

Try this code line please:

df.iloc[-1]

Comments

1

Simply use tail on the whole frame:

df.tail(1)

Or to get a Series use iloc:

df.iloc[-1]

Comments

1

If you want a list:

df.iloc[-1].tolist()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.