简体   繁体   English

pandas - 将附加列添加到现有 csv 文件

[英]pandas - add additional column to an existing csv file

I have 2 files which need to populate the same csv file我有 2 个文件需要填充相同的 csv 文件

To give context, currently, I have this code that prints a CSV in the desired way code-1.py为了给出上下文,目前,我有这个代码以所需的方式打印 CSV 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现在我有 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:我想要做的是在右侧添加一列 Desired Output:

Hand Pose姿势 Eye眼睛
No Seating Back靠背座椅 Left剩下
No Seating Back靠背座椅 Right正确的

However, currently I am getting this,但是,目前我得到了这个,

Actual Output:实际 Output:

Hand Pose姿势
No Seating Back靠背座椅
No Seating Back靠背座椅
0 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基本上,它附加到 CSV 的第一列此外,可以假设 code-2.py 将在 code-1.py 之后立即运行

Appreciate any ideas about this, Thank you!感谢您对此的任何想法,谢谢!

You can't append columns to a csv file without loading it entirely (however, you can append rows).您不能将 append 列添加到 csv 文件而不完全加载它(但是,您可以 append 行)。 Use pd.concat :使用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

with reference to @Corralien's answer参考@Corralien的回答

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我还遇到了一个问题,即每个额外的 append 都会记录在一个新列中,如此处所示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:为了缓解这种情况,我修改了给定的答案并创建了一个额外的 csv 并使用它覆盖了 csv ,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM