【问题标题】:Python - Select different row values from csv and combine them in new csvPython - 从 csv 中选择不同的行值并将它们组合到新的 csv 中
【发布时间】:2020-03-02 08:11:55
【问题描述】:

我有一个csv file,其中包含每小时的波浪状况数据和在特定时间进行的测量数据。我想在测量前 6 小时选择波浪条件和测量结果。我想将其导出到一个新的 csv 文件以进行所有测量。

下面的代码为 1 次测量选择了正确的行:

df = pd.read_csv(csv, header=None, names=['survey', 'time', 'tides', 'mwp', 'swh', 'mwd', 'data1', 'data2', 'data3', 'data4', 'data5'])
xp = [datetime.strptime(d, "%d/%m/%YT%H:%M") for d in df['time']]

xs = mdates.date2num(xp)
date = mdates.DateFormatter ("%d/%m/%Y\n%H:%M")

#select row data waves
survey01 = "26/03/2019T14:00"
survey02 = "10/04/2019T14:00"
survey03 = "11/04/2019T15:00"
survey04 = "01/05/2019T09:00"

#Select row data waves
selected_survey = df.loc[df["time"].eq(survey01)].index[0]
wave = df.loc[selected_survey-6: selected_wave, "time"].index[0]
result_wave = df.loc[wave, ['survey', 'time', 'tides', 'mwp', 'swh', 'mwd']]
meas = df.loc[selected_survey: selected_meas, "time"].index[0]
result_meas = df.loc[meas, ['data1', 'data2', 'data3', 'data4', 'data5']]

#Join them together
joined_list = []
joined_list.extend (result_wave)
joined_list.extend (result_meas)
print (joined_list)

#Export to csv
data = pd.DataFrame(list(zip(*[joined_list]))).add_prefix('Survey1')
data.to_csv('Waves.csv', index=False)
print(data)

应对所有测量(总共 20 多个)执行此操作并合并到 1 个 csv 中

如何为所有这些执行此操作并将其导出到一个 csv 文件?

survey 1  26/03/2019T08:00  1.2 9.34    0.509   1.080  25.5  18.4  31.64    27.3    24.2
survey 2  10/04/2019T08:00  1.1 8.06    1.232   1.155  24.64 19.46 31.844   28.83   25.357
survey 3  ...

或者有没有更简单的方法在 csv 文件中获取正确的数据?

【问题讨论】:

  • 使用apply()selected_survey = df.loc[df["time"].eq(survey01)].index[0]'survey'
  • 感谢您的建议。我尝试使用 apply() 函数,但它没有正确地将必要的数据写入正确的 csv 格式...

标签: python pandas csv export


【解决方案1】:

我无法完全理解代码。但是,正如 cmets 中所讨论的,您可以使用 apply() 来获得所需的结果。

def process_data(i):
    selected_survey = df.loc[df["time"].eq(i)].index[0]
    wave = df.loc[selected_survey-3: selected_wave, "time"].index[0]
    result_wave = df.loc[wave, ['survey', 'time', 'tides', 'mwp', 'swh', 'mwd']]
    meas = df.loc[selected_survey: selected_meas, "time"].index[0]
    result_meas = df.loc[meas, ['data1', 'data2', 'data3', 'data4', 'data5']]

    joined_list = []
    joined_list.extend (result_wave)
    joined_list.extend (result_meas)
    return joined_list

joined_list = df["time"].apply(process_data)

survey_index_list = [f'survey{i}' for i in range(len(joined_list))]
data = pd.DataFrame(list(zip(*[joined_list])), index=survey_index_list)
print(data)

【讨论】:

  • 这个答案有帮助吗?
猜你喜欢
  • 1970-01-01
  • 2020-12-21
  • 1970-01-01
  • 2022-07-27
  • 1970-01-01
  • 1970-01-01
  • 2018-10-14
  • 1970-01-01
  • 2014-12-23
相关资源
最近更新 更多