Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # for https://stackoverflow.com/q/66327949/1431750
- In [1]: import pandas as pd
- In [2]: pd.__version__
- Out[2]: '1.2.2'
- In [3]: df = pd.DataFrame({
- ...: 'Fruits': ['apple', 'orange', 'banana', 'pineapple', 'watermelon'],
- ...: 'Volume 1': [10, 20, 30, 700, 800],
- ...: 'Volume 2': [100, 200, 300, 7000, 8000],
- ...: 'Volume 3': [1, 2, 3, 70, 8],
- ...: 'Volume 4': [9, 8, 7, 6, 5],
- ...: 'Other': [-1, -2, -3, -4, -5]
- ...: })
- ...: df.loc[:, 'Volume 2':'Volume 4'] = df.loc[:, 'Volume 2':'Volume 4'].shift(1)
- ...: df
- Out[3]:
- Fruits Volume 1 Volume 2 Volume 3 Volume 4 Other
- 0 apple 10 NaN NaN NaN -1
- 1 orange 20 100.0 1.0 9.0 -2
- 2 banana 30 200.0 2.0 8.0 -3
- 3 pineapple 700 300.0 3.0 7.0 -4
- 4 watermelon 800 7000.0 70.0 6.0 -5
- In [4]: df = df.dropna()
- ...: df
- Out[4]:
- Fruits Volume 1 Volume 2 Volume 3 Volume 4 Other
- 1 orange 20 100.0 1.0 9.0 -2
- 2 banana 30 200.0 2.0 8.0 -3
- 3 pineapple 700 300.0 3.0 7.0 -4
- 4 watermelon 800 7000.0 70.0 6.0 -5
- In [5]: # will issue warning
- ...: df.loc[:, 'Volume 2':'Volume 4'] = df.loc[:, 'Volume 2':'Volume 4'].astype(int)
- ...: df
- c:\program files\python38\lib\site-packages\pandas\core\indexing.py:1787: SettingWithCopyWarning:
- A value is trying to be set on a copy of a slice from a DataFrame.
- Try using .loc[row_indexer,col_indexer] = value instead
- See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
- self._setitem_single_column(loc, val, pi)
- Out[5]:
- Fruits Volume 1 Volume 2 Volume 3 Volume 4 Other
- 1 orange 20 100 1 9 -2
- 2 banana 30 200 2 8 -3
- 3 pineapple 700 300 3 7 -4
- 4 watermelon 800 7000 70 6 -5
- In [6]: # let's start over but this time, `dropna` after `shift` **in the same cell**:
- ...:
- ...: df = pd.DataFrame({
- ...: 'Fruits': ['apple', 'orange', 'banana', 'pineapple', 'watermelon'],
- ...: 'Volume 1': [10, 20, 30, 700, 800],
- ...: 'Volume 2': [100, 200, 300, 7000, 8000],
- ...: 'Volume 3': [1, 2, 3, 70, 8],
- ...: 'Volume 4': [9, 8, 7, 6, 5],
- ...: 'Other': [-1, -2, -3, -4, -5]
- ...: })
- ...: df.loc[:, 'Volume 2':'Volume 4'] = df.loc[:, 'Volume 2':'Volume 4'].shift(1)
- ...: df = df.dropna()
- ...: df
- Out[6]:
- Fruits Volume 1 Volume 2 Volume 3 Volume 4 Other
- 1 orange 20 100.0 1.0 9.0 -2
- 2 banana 30 200.0 2.0 8.0 -3
- 3 pineapple 700 300.0 3.0 7.0 -4
- 4 watermelon 800 7000.0 70.0 6.0 -5
- In [7]: # NO WARNINGS next...
- ...: df.loc[:, 'Volume 2':'Volume 4'] = df.loc[:, 'Volume 2':'Volume 4'].astype(int)
- ...: df
- Out[7]:
- Fruits Volume 1 Volume 2 Volume 3 Volume 4 Other
- 1 orange 20 100 1 9 -2
- 2 banana 30 200 2 8 -3
- 3 pineapple 700 300 3 7 -4
- 4 watermelon 800 7000 70 6 -5
- In [8]:
Add Comment
Please, Sign In to add comment