still_learning
still_learning

Reputation: 806

Issues in filtering rows using np.where

I am trying to assign values to rows where a condition is verified (True/False).

for i in range(0,3):

new_dataset=df[str(i)][df[str(i)]["Current Amount"] != "3m"]
  for i in range(0,3):
    df[i]['Value'] = np.where(df[i]['Amount']== True, 100, 50)

where i can span from 0 to 3. Value is the new column that I would like to create; Amount is a column already existing in the original dataframe. In the first part, I create new dataframes filtering rows having current amounts equal to 3 million.

However I got the following error:

   /anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py:4: 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
      after removing the cwd from sys.path.

I have tried to follow the steps suggested in this post: How to deal with SettingWithCopyWarning in Pandas?, but it seems that it is still continuing to be not clear to me how to fix the issue.

Could you please help me to fix the issue? I would really appreciate it.

Upvotes: 2

Views: 265

Answers (1)

jezrael
jezrael

Reputation: 862921

Why is not used solution without [i] and compare by True if column is boolean?

df['Value'] = np.where(df['Amount'], 100, 50)

EDIT: Here is necessary DataFrame.copy:

new_dataset=df[str(i)][df[str(i)]["Current Amount"] != "3m"].copy()

Upvotes: 2

Related Questions