0

I have following code to rename column values of a csv

def change_tac_to_label():
    df = pd.read_csv("combined.csv", delimiter=',')
    tacs = df['tac']

    for tac in tacs:
        if float(tac) >= 0.08:
            df['tac'] = "bad"
        else:
            df['tac'] = "good"

    df.to_csv("combined_labeled.csv")

but saved csv file have all tac column values as good. There should be something I am missing here.

What I tried?

  • I tried setting break point at if condition, condition seems to work.
user158
  • 12,852
  • 7
  • 62
  • 94
  • 2
    you can just use `df['tac'] = np.where(df['tac']>=0.08,'bad','good')` inside your function, no need of looping for this usecase., related : [Pandas conditional creation of a series/dataframe column](https://stackoverflow.com/questions/19913659/pandas-conditional-creation-of-a-series-dataframe-column) – anky Apr 13 '21 at 15:01
  • 1
    `df['tac'] = "bad"` rewrite the whole series. So your code basically only looks at the last item. – Quang Hoang Apr 13 '21 at 15:02
  • With your code, you try and create a blank list and keep appending the list with `bad` and `good` according to the conditions and then assign the list to the series. Not tested though – anky Apr 13 '21 at 15:03
  • 1
    @anky thanks it works. – user158 Apr 13 '21 at 15:07
  • @user158 thanks for confirming, I have closed it to the related link since it worked. – anky Apr 13 '21 at 15:07
  • @QuangHoang `df['tac'] = "bad"` is inside a condition though I could not figure things out even with the debugger. – user158 Apr 13 '21 at 15:10

0 Answers0