我想根据年份拆分数据框

时间:2019-02-08 20:51:00

标签: python dataframe split

我有一个数据框,其中包含带有datetime64格式的日期值的列。我想根据年份将数据框拆分为单独的数据框。我在下面写下了代码,虽然可以,但是非常不切实际。

希望有人能提供更好的解决方案!预先装上坦克

Jasmijn

# import libs

import numpy as np
import pandas as pd
from random import sample

# Make some random dataframe with two columns

date = np.arange('2005-02', '2008-03', dtype='datetime64[D]')

status = ["X"]*(int(round(0.9*len(date),0))) +['y']*(int(round(0.05*len(date),0)))+['z']*(int(round(0.05*len(date),0)))
newstatus = sample(status, len(status))

data = {'Data': date, 'Status': newstatus}

df = pd.DataFrame(data)


# Extract year from date and make dummies index for splitting

df['Year'] = pd.DatetimeIndex(df['Data']).year
df = pd.get_dummies(df, columns = ['Year'])

# Split on dummies

df_2007, df_2006, df_2005, df_2008  = df, df, df, df
df_2008= df_2008[df_2008.Year_2008 != 0]
df_2007 = df_2007[df_2007.Year_2007 != 0]
df_2006= df_2006[df_2006.Year_2006 != 0]
df_2005= df_2005[df_2005.Year_2005 != 0]

#Remove Dummies

years = ['Year_2005', 'Year_2006', 'Year_2007', 'Year_2008']
df_2008 = df_2008.drop(years, axis = 1)
df_2007 = df_2007.drop(years, axis = 1)
df_2006 = df_2006.drop(years, axis = 1)
df_2005 = df_2005.drop(years, axis = 1)

1 个答案:

答案 0 :(得分:0)

也许这可以帮助您:

years = df['Data'].dt.year.unique() # I'm guessing Data should be Date really but I'll go along with it.
dfs = {y: df[df['Data'].dt.year == y] for y in years}

这将创建一个dict,其中键是年份,值是与每年相对应的数据框。这意味着dfs[2008]为您提供了包含2008年数据的数据框。