簡體   English   中英

如何在 Python 中將數據分為雨季和旱季?

[英]How to Separate Data into Wet and Dry season in Python?

正在使用的數據圖片

我有一組時間序列數據,按月查看平均風速。 我正在嘗試編寫一些代碼,以便我可以:

  1. 將月份分為干燥(5 月至 10 月)和潮濕(11 月至 4 月)季節。
  2. 生成兩個不同的文件,分別包含每年的旱季和雨季。

我對python相當陌生,所以任何幫助都將不勝感激。

假設您將數據保存在 pandas Dataframe df中。

import pandas as pd

# parse the date to datetime:

date = pd.to_datetime(df['date'], format="%Y-%m")

# Get month numbers for the two seasons
wet_months = [11, 12, 1, 2, 3, 4]
dry_months = [month for month in range(1, 13) if month not in wet_months]

# Now partition the data into two tables
# Select each row that has a month in the given season using `.loc`.

df_wet = df.loc[date.dt.month.isin(wet_months)]
df_dry = df.loc[date.dt.month.isin(dry_months)]

# dataframe index seems to be arbitrary in your question
# so I'd probably drop indexes before saving to file. Or save the file without index.

df_wet = df_wet.reset_index(drop=True)
df_dry = df_dry.reset_index(drop=True)
# This way the tables get new range indexes starting from zero
# instead of remembering their index from the original `df`.

# now go ahead and save to .csv or any other output format
df_wet.to_csv("wet.csv")
df_dry.to_csv("dry.csv")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM