Create tuples of column names and last value from each value in a dataframe

Suppose the interface is outputting the pandas framework like

   df
   A  B
0  1  4
1  2  5
2  3  6

      

And for further processing, only tuples are needed consisting of the column name and the last value of each column, i.e.

A_tuple
('A', 3)
B_tuple
('B', 6)

      

How can I get these tuples in a concise manner from the original frame?

+3


source to share


3 answers


Is this what you want?



In [188]: df.iloc[-1].reset_index().apply(tuple, axis=1)
Out[188]:
0    (A, 3)
1    (B, 6)
dtype: object

      

+3


source


Another method is the call apply

to df, so it iterates over each column and just accesses the last value with [-1]

and the column name via the attribute .name

:



In [208]:
df.apply(lambda x:(x.name ,x.iloc[-1]))

Out[208]:
A    (A, 3)
B    (B, 6)
dtype: object

      

+3


source


Here's a different approach:

df.to_dict('record')[-1].items()

      

What gives:

[('A', 3), ('B', 6)]

      

+3


source







All Articles