【发布时间】:2020-02-14 09:49:54
【问题描述】:
我想将我的输出保存为 .csv。当我运行我的 while 循环并保存输出时,我的输出只保存最后一次迭代。 它没有保存我所有的迭代值。
另外,我想在打印输出时跳过零值行。
这是我的代码:
import pandas as pd `#pandas library
sample = pd.DataFrame(pd.read_csv ("Sample.csv")) #importing .csv as pandas DataFrame
i = 0
while (i <= 23):
print('Value for', i) `#i vale`
sample2 = (sample[sample['Hour'] == i])`#Data for every hour`
sample3 = (sample2[(sample2['GHI']) == (sample2['GHI'].max(0))]) `#Max value from sample3 DataFrame`
sample3 = sample3.loc[sample3.ne(0).all(axis=1)]`ignoring all rows having zero values`
print(sample3) `print sample3`
sample3.to_csv('Output.csv')`trying to save for output after every iteration`
i = i + 1
【问题讨论】:
-
如果你想在迭代后保存,你应该在每次迭代后重命名你的输出,例如
sample3.to_csv(f'Output{i}.csv'). -
或者你可以在 to_csv() 中使用
mode='a'来追加。 -
感谢您的意见。是的,我能够在不覆盖的情况下获取所有数据。但在我的所有迭代之后,我得到了所有的行标题。例如年 月 日 时 分 DHI DNI GHI 露点表面反照率 风向 风速 温度 压力 3917 2005 6 13 5 30 34 363 78 10 0.129 116.5 4 13 1010 年 月 日 时分 DHI DNI GHI 露点表面反照率 风向 风速温度压力 3918 2005 6 13 6 30 62 656 265 11 0.129 134.1 4.8 16 1010 年 月 日 时 分 DHI DNI GHI 露点表面反照率 风向 风速 温度 压力
-
每次迭代后重复打印行标题。我不想这样做
-
@ShriganeshPatil 你可以做的是
if i == 0,然后在 to_csv() 方法中添加header = True。否则header = False.