In [1]:
import pandas as pd
In [21]:
df = pd.DataFrame(randn(6,3),columns = list('ABC'))
In [22]:
df
Out[22]:
A B C
0 -0.031630 -1.867797 1.264133
1 -0.135349 -0.957986 -0.054713
2 0.337048 -0.383348 -1.991538
3 1.009888 -0.779377 -1.481212
4 -0.962852 0.129088 -0.010233
5 -0.640262 0.848540 1.025306
In [33]:
df['D']=0.0
In [34]:
key = 3*[1]+3*[2]
In [35]:
df['key']=key
df
Out[35]:
A B C D key
0 -0.031630 -1.867797 1.264133 0 1
1 -0.135349 -0.957986 -0.054713 0 1
2 0.337048 -0.383348 -1.991538 0 1
3 1.009888 -0.779377 -1.481212 0 2
4 -0.962852 0.129088 -0.010233 0 2
5 -0.640262 0.848540 1.025306 0 2
this doesn't work:
In [36]:
df[df.key==1]['D'] = 1
df
Out[36]:
A B C D key
0 -0.031630 -1.867797 1.264133 0 1
1 -0.135349 -0.957986 -0.054713 0 1
2 0.337048 -0.383348 -1.991538 0 1
3 1.009888 -0.779377 -1.481212 0 2
4 -0.962852 0.129088 -0.010233 0 2
5 -0.640262 0.848540 1.025306 0 2
this does: (why only this way?)
In [39]:
df.D[df.key==1]=3.4
df
Out[39]:
A B C D key
0 -0.031630 -1.867797 1.264133 3.4 1
1 -0.135349 -0.957986 -0.054713 3.4 1
2 0.337048 -0.383348 -1.991538 3.4 1
3 1.009888 -0.779377 -1.481212 0.0 2
4 -0.962852 0.129088 -0.010233 0.0 2
5 -0.640262 0.848540 1.025306 0.0 2
In []: