Home > Net >  pandas - add additional column to an existing csv file
pandas - add additional column to an existing csv file

Time:11-23

I have 2 files which need to populate the same csv file

To give context, currently, I have this code that prints a CSV in the desired way code-1.py

Current Existing added:

array_all = {'Hand': alldata, 'Pose': face_position}
            array_all = {k: pd.Series(v) for k, v in array_all.items()}
            df = pd.DataFrame(array_all)

            df.to_csv('test.csv',
                        mode='w',
                        header=True,
                        index=False)
Hand Pose
No Seating Back
No Seating Back

and now I have code-2.py

Column to add:

   df = pd.DataFrame(results)

    df.to_csv('test.csv',
              mode='a',
              header=True,
              index=False)

what I want this to do is add a column to the right Desired Output:

Hand Pose Eye
No Seating Back Left
No Seating Back Right

However, currently I am getting this,

Actual Output:

Hand Pose
No Seating Back
No Seating Back
0
Right
Left

Basically, it is appending to the first column of the CSV Also, it can be assumed that code-2.py will be run immediately following code-1.py

Appreciate any ideas about this, Thank you!

CodePudding user response:

You can't append columns to a csv file without loading it entirely (however, you can append rows). Use pd.concat:

pd.concat([pd.read_csv('test.csv'), df], axis=1) \
  .to_csv('test.csv', header=True, index=False)
# test.csv before
Hand,Pose
No,Seating Back
No,Seating Back


# test.csv after
Hand,Pose,Eye
No,Seating Back,Left
No,Seating Back,Right

CodePudding user response:

with reference to @Corralien's answer

I additionally faced an issue where each additional append would record in a new column, as shown here https://i.stack.imgur.com/08oTe.png

In order to mitigate this, I modified the given answer and created an additional csv and overwrote the csv using that, as shown below:

     pd.concat([pd.read_csv('test2.csv'), df], axis=1) \
            .to_csv('test.csv', header=True, index=False)

CodePudding user response:

df = (pd.read_csv("test.csv")).assign(Eyes=results)
df.to_csv('test.csv', header=True, index=False)
  • Related