2

I'm new to Pandas, and constantly getting the infamous SettingWithCopyWarning. If I have code like the following I get the warning:

import pandas as pd
import numpy as np

t1 = pd.DataFrame({'A':np.random.randn(8), 'B': np.random.randint(0,4,8)})

table = t1[t1['B'] < 3]

print(table)

table.sort(['B'], inplace=True)

print(table)
  1. In this case, is it just warning me that the original data frame (i.e., 't1') will not be sorted when I run the sort?

  2. Is there a more accepted way to perform this sort of operation (getting a slice of a data frame, and then applying functions on that slice)?

Jeremy
  • 1,960
  • 4
  • 21
  • 42
  • 1
    Well the warning is telling that your op will not affect the orig df, which may be what you intended, if you take a copy of a slice then the warning goes away and it becomes explicit that you are intending to operate on a copy: `table = t1[t1['B'] < 3].copy()` – EdChum Sep 04 '15 at 20:30

2 Answers2

2

Why not make a copy of the slice? Then you will not have the warning.

a = table.copy()

You can read more in the answers to this post How to deal with SettingWithCopyWarning in Pandas?.

Community
  • 1
  • 1
sunny
  • 3,853
  • 5
  • 32
  • 62
1

You can also avoid to use inplace, in this case the copy will be made behind the scene for you.

t1 = pd.DataFrame({'A':np.random.randn(8), 'B': np.random.randint(0,4,8)})
table = t1[t1['B'] < 3]
table = table.sort(['B'])
print(table)
Romain
  • 19,910
  • 6
  • 56
  • 65