The order of the columns has changed after using append when using pandas dataframe

Viewed 286

I use this code to append rows in csv to a new dataframe.

import pandas as pd
from keybert import KeyBERT

df_info = pd.read_csv(r'./old.csv', encoding='utf-8')
df_re = pd.DataFrame()
for index,row in df_info.iterrows():
    doc = row['info']
    model = KeyBERT('distilbert-base-nli-mean-tokens')
    a = model.extract_keywords(doc, keyphrase_ngram_range=(1, 1))
    row['result'] = a
    df_re = df_re.append(row)
df_re.to_csv(r'./new.csv', index=False, mode='w', header=True, encoding='utf-8-sig')

The order of the columns in old.csv is D, info, B, A, C.

But when I use df_re = df_re.append(row), the order of the columns of df_re(new.csv) becomes A, B, C, D, info,result,I don’t want to change the order of the original columns. I just want to append the column result to the last column of the original csv column.

I just need D, info, B, A, C,result in new.csv.

What should I do?

1 Answers

When you initialize df_re it's a blank DataFrame with no row and no column so you shouldn't expect any order. Instead, you can explicitly specify the columns during initialization:

df_re = pd.DataFrame(columns=df_info.columns + ['result'])
Related