![](/img/trans.png)
[英]How to extract row counts based on multiple descriptors in a columns from csv and then export output a new csv using bash/python script?
[英]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.