1

How can the following MWE script work? I actually want the assignment (right before the print) to fail. Instead it changes nothing and raises no exception. This is some of the weirdest behaviour.

import pandas as pd
import numpy as np
l = ['a', 'b']
d = np.array([[False]*len(l)]*3)
df = pd.DataFrame(columns=l, data=d, index=range(1,4))
df["a"][4] = True
print df

1 Answer 1

1

When you say df["a"][4] = True, you are modifying the a series object, and you aren't really modifying the df DataFrame because df's index does not have an entry of 4. I wrote up a snippet of code exhibiting this behavior:

In [90]:

import pandas as pd
import numpy as np
l = ['a', 'b']
d = np.array([[False]*len(l)]*3)
df = pd.DataFrame(columns=l, data=d, index=range(1,4))
df['a'][4] = True

print "DataFrame:"
print df

DataFrame:
       a      b
1  False  False
2  False  False
3  False  False

In [91]:

df['b'][4]=False
print "DataFrame:"
print df

DataFrame:
       a      b
1  False  False
2  False  False
3  False  False

In [92]:

print "DF's Index"
print df.index

DF's Index
Int64Index([1, 2, 3], dtype='int64')

In [93]:

print "Series object a:" 
print df['a']

Series object a:
1    False
2    False
3    False
4     True
Name: a, dtype: bool

In [94]:

print "Series object b:" 
print df['b']

Series object b:
1    False
2    False
3    False
4    False
Name: b, dtype: bool
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the reply. In a nutshell underlying it is a dict. Hmmm. Is there any way to do assignment with key checking? That is other than if key in df.index. Would prefer something that raises an exception.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.