Python Forum
Adding row to df with df.loc[len(df.index)]
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Adding row to df with df.loc[len(df.index)]
#1
This works to add a list a as a new (last) row of a dataframe df:

df.loc[len(df.index)] = a
len(df.index) is an integer, right? I'm confused about why this works because I thought unlike .iloc[] that takes integer locations (but is unable to expand the size of a dataframe), .loc[] takes labels.

Thanks!
Reply
#2
import pandas as pd

df = pd.DataFrame({"A":range(5), "B":range(5,10)})
print(df)

df.loc[42] = ("Meaning", "Everything")
print(df)
Output:
A B 0 0 5 1 1 6 2 2 7 3 3 8 4 4 9 A B 0 0 5 1 1 6 2 2 7 3 3 8 4 4 9 42 Meaning Everything
You are correct about iloc() and loc(). You are confused thinking that "len(df.index)" in "df.loc[len(df.index)] = a" is an integer index. It is a label. It just happens to also be an integer.
Reply
#3
(May-05-2022, 07:49 PM)deanhystad Wrote: You are correct about iloc() and loc(). You are confused thinking that "len(df.index)" in "df.loc[len(df.index)] = a" is an integer index. It is a label. It just happens to also be an integer.

This helps. Thanks.

I think what's confusing is that the basic examples I've seen given for .loc[] and .iloc[] will show have string labels for the former and integers for the latter. Here, 42 is a label that also happens to be an integer--like you say. At some point, though, I'd be inclined to ask "what's the difference?" For example, if L6 is:
df.loc[5] = ("Meaning", "Everything")
Evidently, it's not the case that labels can't be integers. It is the case that arguments for .loc[] must be labels--and that is all. If the index is numeric then numeric labels are fine. If the index is string then string labels it must be. Is that accurate?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Adding markers to Folium map only adding last element. tantony 0 2,168 Oct-16-2019, 03:28 PM
Last Post: tantony

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020