I'm using .loc to filter my DataFrame and set values from another column. Here's a short example, first setting up a simple DataFrame:
df = pd.DataFrame({
'name': ['Steve', 'Julie', 'Dan', 'Mary'],
'nickname': ['Steve-o', 'Jules', '', '']
})
# name nickname
# 0 Steve Steve-o
# 1 Julie Jules
# 2 Dan
# 3 Mary
Next I replace the missing values using .loc like this:
df.loc[df['nickname'] == '', 'nickname'] = df['name']
# name nickname
# 0 Steve Steve-o
# 1 Julie Jules
# 2 Dan Dan
# 3 Mary Mary
Why does this even work? I'm assigning a series of a different length, how does it know to only match the items with the same index number? Why doesn't it throw an error about the series being different lengths? This just seems very magical to me and it makes me nervous.
After lots of searching, I can't find any examples of this approach in the official documentation. I have seen a few rare examples of this out in the wild, but with no explanation or reassurance that it's a correct approach.