0

I am trying to delete the first few characters of each row in a dataframe and getting an error. I am quite new to pandas, trying to learn though. I don't quite get what the warning means, and why it is showing up.

The problem:

As an example:

import pandas as pd

df = {
    'Heading':['Line 1', 'Line 2','Line 3'],
    'Text'   :['blabla useful info', 'xyxyxy useful info', 'abcabc useful info']
    }

df = pd.DataFrame(d)

I want to remove the first 7 characters because I know that after that the useful info starts. To do this, I am using the solution described here:

df['Text'] = df['Text'].str[7:] 

However, when doing this, it results in a SettingWithCopyWarning, like this:

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 

This error does not occur whenever I filter the dataframe like this just before tying to slice:

df = df[df['Text'].str.contains('stuff')]
df['Text'] = df['Text'].str[7:] 

Some background info

I am getting the dataframe from a list of other dataframes. This list was made by filtering a very large dataframe with different information in a specific row. I wanted to split this large frame based on the type of information in this specific row, and then apply data edits to the information.

So the list contains:

[dataframe with info x,
dataframe with info y,
dataframe with info z]

I want to do a certain thing with info x, another thing with info y and a third thing with info z. This can probably be done with combining the groupby() and apply() functions as well, so if that is easier or more convenient, enlighten me!

  • Your issue is due to something that you did prior to this code. The workaround is `df = df.copy()` – mozway May 17 '23 at 11:30
  • How does this workaround work? Do you then just work with 2 versions of the same dataframe? Isn't that a bad idea? What could I have done in my previous code that could make such an error appear? – MrTomatosoup May 19 '23 at 07:38
  • Please read the duplicated question in detail, there are several reasons why this could have happened and it's difficult to know without the full code. – mozway May 19 '23 at 08:43

0 Answers0