I have a dataframe
with different columns, nombre
, cantidad
, batería
. Which can have a form similar to the following.
data = [['dev1', 20, '65'],
['dev1', 4, '99'],
['dev2', 22, '67'],
['dev1', 6, '99'],
['dev3', 20, '85']
['dev3', 35, '33']
]
columnas = ['nombre', 'cantidad', 'bateria']
df = pd.DataFrame(data, columns=columnas)
What I want is to obtain the final value for each element, in this case recognized by its name. That is, for the example above I need an output that was.
lista= [[dev2,22,67],[dev1,6,99],[dev3,35,33]]
Therefore I do:
# Obtengo los diferentes elementos que contiene la columna nombre
elems = list(set(df['nombre']))
# Últimos valores de cada nodo
lista, values = [], []
for el in elems:
ndf = df.loc[df['Node name'] == el]
values.append(ndf['nombre'].iloc[-1])
values.append(ndf['cantidad'].iloc[-1])
values.append(ndf['bateria'].iloc[-1])
lista.append(values)
But what remains for me is ['dev2',22,67,'dev1',6,99,'dev3',35,33]
how do I make it stay the other way?
Is there a more efficient way to do this data fetching process? I imagine it pandas
allows us to do it faster and better.
Thank you!
groupby()
You can use the and methodtail()
like this:And adding
.values.tolist()
the list is obtained (suggested by @abulafia), if the result as DataFrame does not work for you:EDIT: Although this is functional, in the end I implemented @gustavovelascoh's answer and @abulafia's suggestion. Shorter and simpler with the desired results.
In the end my solution was to initialize the list
values
inside the loop so that it resets on each iteration.