【问题标题】:How to save output in .csv after every loop without overwriting in Pandas?如何在每次循环后将输出保存在 .csv 中而不用 Pandas 覆盖?
【发布时间】: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.

标签: python pandas dataframe


【解决方案1】:

做你想做的另一种方法是摆脱你的循环,像这样:

sample_with_max_ghi = sample.assign(max_ghi=sample.groupby('Hour')['GHI'].transform('max'))
sample_filtered = sample_with_max_ghi[sample_with_max_ghi['GHI'] == sample_with_max_ghi['max_ghi']]
output_sample = sample_filtered.loc[sample_filtered.ne(0).all(axis=1)].drop('max_ghi', axis=1)
output_sample.to_csv('Output.csv')

一些解释:

1.

sample_with_max_ghi = sample.assign(max_ghi=sample.groupby('Hour')['GHI'].transform('max'))

此行向您的数据框添加一个新列,其中包含 Hour 组的 GHI 列的最大值

2.

sample_filtered = sample_with_max_ghi[sample_with_max_ghi['GHI'] == sample_with_max_ghi['max_ghi']]

此行仅过滤 GHI 值实际上是其 Hour 组的最大值的行

3.

output_sample = sample_filtered.loc[sample_filtered.ne(0).all(axis=1)].drop('max_ghi', axis=1)

并应用最后一个过滤器去除 0 值行

【讨论】:

  • 谢谢你这个代码也很正常
【解决方案2】:

在循环运行时,在每个循环中添加值以重命名 csv 文件将使其看起来独一无二并解决您的问题。例如:

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(str(i)+'Output.csv')`trying to save for output after every iteration`
    i = i + 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-08
    • 2019-06-04
    • 1970-01-01
    • 2020-11-30
    • 1970-01-01
    • 2019-09-20
    • 2019-02-20
    • 1970-01-01
    相关资源
    最近更新 更多