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!
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.
(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?