Df.loc [rows, [col]] vs df.loc [rows, col] in assignment

What do the following assignments do differently?

df.loc[rows, [col]] = ...
df.loc[rows, col] = ...

      

For example:

r = pd.DataFrame({"response": [1,1,1],},index = [1,2,3] )
df = pd.DataFrame({"x": [999,99,9],}, index = [3,4,5] )
df = pd.merge(df, r, how="left", left_index=True, right_index=True)

df.loc[df["response"].isnull(), "response"] = 0
print df
     x  response
3  999       0.0
4   99       0.0
5    9       0.0

      

but

df.loc[df["response"].isnull(), ["response"]] = 0
print df
     x  response
3  999       1.0
4   99       0.0
5    9       0.0

      

why should I expect the former to behave differently in the latter?

+3


source to share


1 answer


df.loc[df["response"].isnull(), ["response"]]

      

returns a DataFrame, so if you want to assign something to it, it must be aligned with both index and columns

Demo:

In [79]: df.loc[df["response"].isnull(), ["response"]] = \
             pd.DataFrame([11,12], columns=['response'], index=[4,5])

In [80]: df
Out[80]:
     x  response
3  999       1.0
4   99      11.0
5    9      12.0

      



alternatively you can assign an array / matrix of the same shape:

In [83]: df.loc[df["response"].isnull(), ["response"]] = [11, 12]

In [84]: df
Out[84]:
     x  response
3  999       1.0
4   99      11.0
5    9      12.0

      

I would also consider using the method fillna()

:

In [88]: df.response = df.response.fillna(0)

In [89]: df
Out[89]:
     x  response
3  999       1.0
4   99       0.0
5    9       0.0

      

+4


source







All Articles