簡體   English   中英

將python腳本輸出變量導出到python中csv中的不同列

[英]export python script output variable to different columns in csv in python

我的python腳本將輸出提供給4個變量,例如

output = (x, y, attributes1, attributes2)
print(output)

輸出像

('Location', 'People', ['USA', 'UK', 'Brazil'], ['Mohit', 'Aryan'])
('People', 'College', ['Mohit', 'Aryan', 'Tom'], ['Havard', 'Oxford'])....
and thousands of output like this

where 'Location' is x variable
  'People' is y variable
  ['USA', 'UK', 'Brazil'] is attributes1 and 
  ['Mohit', 'Aryan'] is attributes2

因此,如何將這四個變量(x,y,attributes1,attributes2)導出到csv文件中,以便不同的變量進入不同的列。

輸出將像:

x                 y            attributes1            attributes2
Location         People     ['USA', 'UK', 'Brazil']    ['Mohit', 'Aryan']
People           College    ['Mohit', 'Aryan', 'Tom']  ['Havard', 'Oxford']

使用pandas因為它可以很好地放大。 例如,

import pandas as pd
x = 'Loacation'
y = 'People'
attribute1 = ['USA', 'UK', 'Brazil']
attribute2 = ['Mohit', 'Aryan']

df = pd.DataFrame([x, y, attribute1, attribute2],
         index = ('x', 'y', 'attribute1', 'attribute2')).transpose()

with open(r'D:\file.txt', 'w') as f:
    f.write(df.to_string())

輸出:

           x       y         attribute1      attribute2
0  Loacation  People  [USA, UK, Brazil]  [Mohit, Aryan]

或對於excel文件,將最后兩行替換為

writer = pd.ExcelWriter(r'D:\text.xlsx')
df.to_excel(writer,'Sheet1')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM