Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why some commands cause an error relative to the preceding command?

This is a pandas question.

Try to copy this in Jupyter Notebook:

In [1]: df = pd.DataFrame([[1, 2], [4, 5], [7, 8]],
        index=['cobra', 'viper', 'sidewinder'],
        columns=['max_speed', 'shield'])

        df
In [2]: df.pop('shield') # Return as series.
In [3]: pd.DataFrame(df.pop('shield')) # Return as DataFrame.

Then inverse it to the sequence of

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

In[1]

In[3]

In[2]

Why the 3rd Out[-] always cause an error?

I oftentimes encounter this kinds of error. Is this a cache issue? Redundancy? What is the reason why such error occurs?

>Solution :

I think your code generate expected error:

df = pd.DataFrame([[1, 2], [4, 5], [7, 8]],
        index=['cobra', 'viper', 'sidewinder'],
        columns=['max_speed', 'shield'])

Here DataFrame.pop take column shield from original Dataframe, create Series and drop from original:

a = df.pop('shield') # Return as series.
print (a)
cobra         2
viper         5
sidewinder    8
Name: shield, dtype: int64

So no column in df after pop:

print (df)
            max_speed
cobra               1
viper               4
sidewinder          7

So failed get column shield, because not exist in df:

b = pd.DataFrame(df.pop('shield')) # Return as DataFrame.
print (b)
KeyError: 'shield'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading