[英]How to read and write to CSV Files in Python
我有一个csv文件,它只有一个column,作为我的输入。
我使用该输入来查找我的输出。 我有多个输出,我需要将这些输出放在另一个csv文件中。
有人可以建议我如何做的方法吗?
这是代码:
import urllib.request
jd = {input 1}
//
Some Codes to find output - a,b,c,d,e
//
** Code to write output to a csv file.
** Repeat the code with next input of input csv file.
Input CSV File has only a single column and is represented below:
1
2
3
4
5
Output would in a separate csv in a given below format :
It would be in multiple rows and multiple columns format.
a b c d e
这是一个简单的示例:
data.csv是具有一列和多行的csv。
result.csv包含输入的平均值和中位数,并且是具有1行2列的csv(均值在第一列中,中位数在第二列中)
例:
import numpy as np
import pandas as pd
import csv
#load the data
data = pd.read_csv("data.csv", header=None)
#calculate things for the 1st column that has the data
calculate_mean = [np.mean(data.loc[:,0])]
calculate_median = [np.median(data.loc[:,0])]
results = [calculate_mean, calculate_median]
#write results to csv
row = []
for result in results:
row.append(result)
with open("results.csv", "wb") as file:
writer = csv.writer(file)
writer.writerow(row)
我认为您需要read_csv
才能将文件读取到Series
并且需要to_csv
以便将输出Series
写入到Series.iteritems
循环中的文件中。
#file content
1
3
5
s = pd.read_csv('file', squeeze=True, names=['a'])
print (s)
0 1
1 3
2 5
Name: a, dtype: int64
for i, val in s.iteritems():
#print (val)
#some operation with scalar value val
df = pd.DataFrame({'a':np.arange(val)})
df['a'] = df['a'] * 10
print (df)
#write to csv, file name by val
df.to_csv(str(val) + '.csv', index=False)
a
0 0
a
0 0
1 10
2 20
a
0 0
1 10
2 20
3 30
4 40
在伪代码中,您将执行以下操作:
for each_file in a_folder_that_contains_csv: # go through all the `inputs` - csv files
with open(each_file) as csv_file, open(other_file) as output_file: # open each csv file, and a new csv file
process_the_input_from_each_csv # process the data you read from the csv_file
export_to_output_file # export the data to the new csv file
现在,我不会写一个完整的示例,因为最好是您开始挖掘并在有疑问时问一些具体问题。 您现在只是在问: 因为我不了解Python,所以请为我编写此代码 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.