Home > Software engineering >  Cannot drop an unnamed column in a csv in pandas
Cannot drop an unnamed column in a csv in pandas

Time:06-29

Trying to drop a unnamed column from a dataframe created from a CSV but it won't drop.

for m in mlist: #Loop through each month
    print('Running merge for ' str(m) ' collecting csv files...')
    csvlist = [i for i in glob.glob(str(m) '2019_G*.{}'.format('csv'))] #List all the CSVs of each month
    month_csv = pd.concat([pd.read_csv(csv) for csv in csvlist])
    month_csv = month_csv.astype({unique_gridid:'int'})
    month_csv = month_csv.set_index(unique_gridid)
    month_csv.columns.str.match("Unnamed")
    month_csv.loc[:,~month_csv.columns.str.match("Unnamed")]
    month_csv.drop("Unnamed: 0", axis=1)
    print(month_csv)

Console still shows the unnamed column in the print output.

CodePudding user response:

The issue is with the following call:

month_csv.drop("Unnamed: 0", axis=1)

The drop function has a inplace parameter that, by default, is equal to False. Therefore, the function returns a new dataframe with the dropped column. You have two options:

month_csv.drop("Unnamed: 0", axis=1, inplace=True)

or

month_csv = month_csv.drop("Unnamed: 0", axis=1)
  • Related