如何将每次迭代的结果附加到CSV文件中?

时间:2018-11-15 17:07:40

标签: python pandas dataframe

我将数值字段发送到for循环中,并计算最大值,最小值和百分位数。我想将每个结果(最后打印的语句)存储到csv文件中。我真的被这打了。

for循环打印中的每个迭代结果如下:

emp_id, 10, 23, 45.4

我想将这些结果保存到一个csv文件中。

import pandas as pd
import numpy as np

data = pd.read_csv(r'C:\Users\spanda031\Downloads\test_19.csv')
#abc=data.dtypes
#print(abc)
df = data.select_dtypes(include='number')
cols = df.columns.values
print(cols)
arr = df.values
#print("new array ", arr)
#with open(r'C:\Users\spanda031\Downloads\test_19.csv') as f:
#    d_reader = csv.DictReader(f)

    #get fieldnames from DictReader object and store in list
#    headers = d_reader.fieldnames
#    print(headers)
for line in cols:
        #print value in MyCol1 for each row
        #print(line)        
        v3=np.array(data[line])
        #print(v3)        
        print(line,",",v3.min(),",",v3.max(),",",np.percentile(v3, 25))

1 个答案:

答案 0 :(得分:0)

这样我可以解决它。

res_df=line,v3.min(),v3.max(),np.percentile(v3, 25),np.std(v3)      
    with open('C:\\Users\\spanda031\\Downloads\\abccc.csv', 'a', newline='') as csvfile:
        writerows = csv.writer(csvfile, delimiter=',',
                        quotechar='"', quoting=csv.QUOTE_MINIMAL)
        writerows.writerow(map(lambda x: x, res_df))