Borja_042
Borja_042

Reputation: 1071

.loc The same column at once with pandas

This might be a rather useless question but I would like to learn how to do .loc for same column sliced by rows at same time. Lets imagine I have this df:

k1 = pd.DataFrame([1,2,3,4])
k2 = pd.DataFrame( [5,6,7,8])
k3 =  pd.DataFrame([9,10,11,12])
frames = [k1,k2,k3]
k4 = pd.concat(frames, axis = 1).T
k4.loc[1] = 'HOla'
k4.loc[2] = 'Bye'
k4 = k4.reset_index()
k4.loc[0,4]= 0.00
k4.loc[1:2,4]= 288
k4.loc[3:,4]= 'New'

How could I update column 4 with just 1 sentence, or is it impossible? Thanks in advance.

Upvotes: 1

Views: 644

Answers (1)

jezrael
jezrael

Reputation: 862701

You need : for select all rows:

#if need update column 4 to value 1
k4.loc[:, 4] = 1
#if need update column 3 to value a
k4.loc[:, 3] = 'a'
#for select row : can be omit
#if need update row 3 to value b
k4.loc[3] = 'b'
#if need update row 2 to value c
k4.loc[2, :] = 'c'
print (k4)
  index    0    1    2  3            4
0     0    1    2    3  a            1
1     0    5    6    7  a  some string
2     c    c    c    c  c            c
3     b    b    b    b  b            b
4     2  Bye  Bye  Bye  a            1

Upvotes: 1

Related Questions