熊猫追加到同一行而不是新行

时间:2020-05-07 15:05:25

标签: python-3.x pandas csv

我正在搜索给定值的多个CSV。找到该值后,包含该值的整行应附加到另一个csv(to_be_appended.csv)。代替将该行写在最后一行的正下方,而是将复制的值放在最后一行的末尾。

# to_be_copied.csv
         Device  |   ID  |  Color  
     Galaxy S8   | 1234  |    Red
     Galaxy S8   | 1235  |   Blue
# to_be_appended.csv
         Device  |   ID   | Color  
     OnePlus 6T  |  1237  |  Black

运行此代码:

to_be_copied = pd.read_csv('to_be_copied.csv')
to_be_appended = pd.read_csv('to_be_appended.csv')

ID_to_move = "1235"

location_of_ID = to_be_copied.loc[to_be_copied['ID'] == ID_to_move].index[0]
row_of_id = to_be_copied.loc[location_of_ID : location_of_ID]

with open('to_be_appended.csv', 'a') as to_be_appended:
        row_of_id.to_csv(to_be_appended, header=False)

产生以下结果:

# to_be_appended.csv
         Device  |   ID   | Color  
     OnePlus 6T  |  1237  |  Black | Galaxy S8   | 1235  |   Blue

但是我需要它来产生这个结果

# to_be_appended.csv
         Device  |   ID   | Color  
     OnePlus 6T  |  1237  |  Black 
      Galaxy S8  |  1235  |   Blue

是什么原因造成的?我将如何解决?如果我使用xlsx文件,结果会有所不同吗?

0 个答案:

没有答案