简体   繁体   English

Python:将数据写入csv文件

[英]Python: Write data to csv file

Coming from Matlab to Python, so I am a bit confused. 从Matlab到Python,我有点困惑。

I have a script which calculates Wave Period, Wave Number, Wave Height and RAOs for a number of runs. 我有一个脚本,可以计算多次运行的波浪周期,波浪数,波浪高度和RAO。 For example are the RAO arrays created like this in a loop: 例如,在循环中创建的RAO数组如下:

# Calculation of RAO

rao_2[j] = sway[j]/wave[j]
rao_3[j] = heave[j]/wave[j]
rao_4[j] = roll[j]/(k[j]*wave[j])

I want to save all the information in a CSV file where I want the rows to be each run and the columns are 'Period', 'Wave Number', 'Wave', 'RAO' etc. 我想将所有信息保存在一个CSV文件中,我希望每行都在其中行,列是“句点”,“波数”,“波”,“ RAO”等。

I have tried to use the following method: 我尝试使用以下方法:

prelim_data = list(zip(T, k, wave, wave_front, wave_back, rao_2, rao_3, rao_4))

df = pd.DataFrame(data=prelim_data, columns=['Period', 'Wave Number', 'Wave', 'Front Wave', 'Back Wave', 'RAO 2', 'RAO 3', 'RAO 4'])

df.to_csv(pre_fid1, index=False, header=False)

But this seems to write it all into one list in one column, which isn't a too big of a deal. 但这似乎将所有内容写在一个列表中的一列中,这没什么大不了的。 But the problem arises when I want to combine the five CSV files from five different runs into one big one. 但是,当我要将五个不同运行的五个CSV文件合并为一个大文件时,就会出现问题。

They have different amount of rows but the same amount of columns, but when I combine them like this: 它们具有不同数量的行,但具有相同数量的列,但是当我像这样组合它们时:

import pandas as pd

pieces = []

for num in [8, 9, 10, 11, 12, 13, 14, 15]:
    s = pd.read_csv('main/prelim_results%d.csv' % num, header=1)
    print('Reading Number: ', num)
    print(s.loc[0][0])
    pieces.append(s)

newcsv = pd.concat(pieces, axis=0)
newcsv.to_csv('main/prelim_main.csv', index=0, header=0)

data = pd.read_csv('main/prelim_main.csv', header=None)

The first CSV file is written into the first row.. What am I doing wrong? 第一个CSV文件写入第一行。我在做什么错?

Is there a better way to save my data and combine it into one file? 有没有更好的方法来保存我的数据并将其组合到一个文件中?

Thanks for any help 谢谢你的帮助

Try below code : 试试下面的代码:

import pandas as pd
pieces = []
for num in range(8,16):
    s = pd.read_csv('main/prelim_results%d.csv' % num)
    print (s.head())
    print('Reading Number: ', num)
    pieces.append(s)
newcsv = pd.concat(pieces, axis=0)
newcsv.to_csv('main/prelim_main.csv', index=0, header=0)
data = pd.read_csv('main/prelim_main.csv', header=None)
print (data.head())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM