0

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!

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.sstatic.net/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)

Comments

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

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.