I have the following code:
import pandas as pd
df = pd.DataFrame(columns = ['A', 'B', 'C', 'D'])
df = df.append({'A': ['AB', 'C', 'CD', 'DC']}, ignore_index = True)
df.to_csv('df.csv', index = False)
# Another place in the code
a = 5
df = pd.read_csv('df.csv')
df = df.append({'B': a}, ignore_index = True)
df.to_csv('df.csv', index = False)
The code gives:
Desired result:
How to correct the code, please? I would like to set indexes when ['AB', 'C', 'CD', 'DC'] list is loaded.
CodePudding user response:
IIUC use:
df = pd.concat([df, pd.DataFrame({'A': ['AB', 'C', 'CD', 'DC']})])
Your solution:
df = df.append(pd.DataFrame({'A': ['AB', 'C', 'CD', 'DC']}))
In another columns are created missing values, so is possible replace them by:
a = 5
df = df.fillna(pd.DataFrame({'B': a}, index=[0]))
Another idea:
df.loc[0, 'B'] = a