我正在从csv创建一个DataFrame,如下所示:
stock = pd.read_csv('data_in/' + filename + '.csv', skipinitialspace=True)
Run Code Online (Sandbox Code Playgroud)
DataFrame有一个日期列.有没有办法创建一个新的DataFrame(或只是覆盖现有的DataFrame),它只包含日期值在指定日期范围内或两个指定日期值之间的行?
unu*_*tbu 339
有两种可能的解决方案:
df.loc[mask]df[start_date : end_date]使用布尔掩码:
确保df['date']是带有dtype的系列datetime64[ns]:
df['date'] = pd.to_datetime(df['date'])
Run Code Online (Sandbox Code Playgroud)
制作一个布尔掩码.start_date并且end_date可以是datetime.datetimes,
np.datetime64s,pd.Timestamps甚至是datetime字符串:
#greater than the start date and smaller than the end date
mask = (df['date'] > start_date) & (df['date'] <= end_date)
Run Code Online (Sandbox Code Playgroud)
选择子DataFrame:
df.loc[mask]
Run Code Online (Sandbox Code Playgroud)
或重新分配给 df
df = df.loc[mask]
Run Code Online (Sandbox Code Playgroud)
例如,
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.random((200,3)))
df['date'] = pd.date_range('2000-1-1', periods=200, freq='D')
mask = (df['date'] > '2000-6-1') & (df['date'] <= '2000-6-10')
print(df.loc[mask])
Run Code Online (Sandbox Code Playgroud)
产量
0 1 2 date
153 0.208875 0.727656 0.037787 2000-06-02
154 0.750800 0.776498 0.237716 2000-06-03
155 0.812008 0.127338 0.397240 2000-06-04
156 0.639937 0.207359 0.533527 2000-06-05
157 0.416998 0.845658 0.872826 2000-06-06
158 0.440069 0.338690 0.847545 2000-06-07
159 0.202354 0.624833 0.740254 2000-06-08
160 0.465746 0.080888 0.155452 2000-06-09
161 0.858232 0.190321 0.432574 2000-06-10
Run Code Online (Sandbox Code Playgroud)
使用DatetimeIndex:
如果您要按日期进行大量选择,则可以更快地将date列设置
为索引.然后,您可以使用日期选择行
df.loc[start_date:end_date].
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.random((200,3)))
df['date'] = pd.date_range('2000-1-1', periods=200, freq='D')
df = df.set_index(['date'])
print(df.loc['2000-6-1':'2000-6-10'])
Run Code Online (Sandbox Code Playgroud)
产量
0 1 2
date
2000-06-01 0.040457 0.326594 0.492136 # <- includes start_date
2000-06-02 0.279323 0.877446 0.464523
2000-06-03 0.328068 0.837669 0.608559
2000-06-04 0.107959 0.678297 0.517435
2000-06-05 0.131555 0.418380 0.025725
2000-06-06 0.999961 0.619517 0.206108
2000-06-07 0.129270 0.024533 0.154769
2000-06-08 0.441010 0.741781 0.470402
2000-06-09 0.682101 0.375660 0.009916
2000-06-10 0.754488 0.352293 0.339337
Run Code Online (Sandbox Code Playgroud)
虽然Python列表索引(例如seq[start:end]包括start但不包括),但是如果它们在索引中end,则Pandas 在结果中df.loc[start_date : end_date]包括两个端点.然而,既不start_date也不必end_date在索引中.
另请注意,pd.read_csv有一个parse_dates参数可用于将date列解析为datetime64s.因此,如果您使用parse_dates,则不需要使用df['date'] = pd.to_datetime(df['date']).
小智 49
我觉得最好的选择是使用直接检查而不是使用loc函数:
df = df[(df['date'] > '2000-6-1') & (df['date'] <= '2000-6-10')]
Run Code Online (Sandbox Code Playgroud)
这个对我有用.
带切片的loc函数的主要问题是限制应该存在于实际值中,否则会导致KeyError.
pom*_*ber 23
您还可以使用between:
df[df.some_date.between(start_date, end_date)]
Run Code Online (Sandbox Code Playgroud)
Jon*_*oks 18
您可以像这样isin在date列
上使用该方法df[df["date"].isin(pd.date_range(start_date, end_date))]
注意:这仅适用于日期(如问题所示)而非时间戳.
例:
import numpy as np
import pandas as pd
# Make a DataFrame with dates and random numbers
df = pd.DataFrame(np.random.random((30, 3)))
df['date'] = pd.date_range('2017-1-1', periods=30, freq='D')
# Select the rows between two dates
in_range_df = df[df["date"].isin(pd.date_range("2017-01-15", "2017-01-20"))]
print(in_range_df) # print result
Run Code Online (Sandbox Code Playgroud)
这使
0 1 2 date
14 0.960974 0.144271 0.839593 2017-01-15
15 0.814376 0.723757 0.047840 2017-01-16
16 0.911854 0.123130 0.120995 2017-01-17
17 0.505804 0.416935 0.928514 2017-01-18
18 0.204869 0.708258 0.170792 2017-01-19
19 0.014389 0.214510 0.045201 2017-01-20
Run Code Online (Sandbox Code Playgroud)
强烈建议将日期列转换为索引。这样做会提供很多便利。一种是轻松选择两个日期之间的行,您可以看到这个示例:
import numpy as np
import pandas as pd
# Dataframe with monthly data between 2016 - 2020
df = pd.DataFrame(np.random.random((60, 3)))
df['date'] = pd.date_range('2016-1-1', periods=60, freq='M')
Run Code Online (Sandbox Code Playgroud)
2017-01-01要选择和之间的行2019-01-01,您只需将该date列转换为index:
df.set_index('date', inplace=True)
Run Code Online (Sandbox Code Playgroud)
然后只进行切片:
df.loc['2017':'2019']
Run Code Online (Sandbox Code Playgroud)
您可以在直接读取 csv 文件时选择日期列作为索引,而不是df.set_index():
df = pd.read_csv('file_name.csv',index_col='date')
Run Code Online (Sandbox Code Playgroud)
保持解决方案简单和Pythonic,建议您尝试一下。
如果要经常执行此操作,最好的解决方案是首先将date列设置为索引,这将转换DateTimeIndex中的列,并使用以下条件来分割任何日期范围。
import pandas as pd
data_frame = data_frame.set_index('date')
df = data_frame[(data_frame.index > '2017-08-10') & (data_frame.index <= '2017-08-15')]
Run Code Online (Sandbox Code Playgroud)
另一种选择,如何实现这一点,是通过使用pandas.DataFrame.query()方法。让我向您展示以下名为df.
>>> df = pd.DataFrame(np.random.random((5, 1)), columns=['col_1'])
>>> df['date'] = pd.date_range('2020-1-1', periods=5, freq='D')
>>> print(df)
col_1 date
0 0.015198 2020-01-01
1 0.638600 2020-01-02
2 0.348485 2020-01-03
3 0.247583 2020-01-04
4 0.581835 2020-01-05
Run Code Online (Sandbox Code Playgroud)
作为参数,使用条件进行过滤,如下所示:
>>> start_date, end_date = '2020-01-02', '2020-01-04'
>>> print(df.query('date >= @start_date and date <= @end_date'))
col_1 date
1 0.244104 2020-01-02
2 0.374775 2020-01-03
3 0.510053 2020-01-04
Run Code Online (Sandbox Code Playgroud)
如果您不想包含边界,只需更改如下条件即可:
>>> print(df.query('date > @start_date and date < @end_date'))
col_1 date
2 0.374775 2020-01-03
Run Code Online (Sandbox Code Playgroud)
pandas0.22有一个between()功能。使回答这个问题更容易和更易读的代码。
# create a single column DataFrame with dates going from Jan 1st 2018 to Jan 1st 2019
df = pd.DataFrame({'dates':pd.date_range('2018-01-01','2019-01-01')})
Run Code Online (Sandbox Code Playgroud)
假设您想获取 2018 年 11 月 27 日和 2019 年 1 月 15 日之间的日期:
# use the between statement to get a boolean mask
df['dates'].between('2018-11-27','2019-01-15', inclusive=False)
0 False
1 False
2 False
3 False
4 False
# you can pass this boolean mask straight to loc
df.loc[df['dates'].between('2018-11-27','2019-01-15', inclusive=False)]
dates
331 2018-11-28
332 2018-11-29
333 2018-11-30
334 2018-12-01
335 2018-12-02
Run Code Online (Sandbox Code Playgroud)
注意inclusive论证。当你想明确你的范围时非常有帮助。请注意,当设置为 True 时,我们也会返回 2018 年 11 月 27 日:
df.loc[df['dates'].between('2018-11-27','2019-01-15', inclusive=True)]
dates
330 2018-11-27
331 2018-11-28
332 2018-11-29
333 2018-11-30
334 2018-12-01
Run Code Online (Sandbox Code Playgroud)
这种方法也比前面提到的isin方法更快:
%%timeit -n 5
df.loc[df['dates'].between('2018-11-27','2019-01-15', inclusive=True)]
868 µs ± 164 µs per loop (mean ± std. dev. of 7 runs, 5 loops each)
%%timeit -n 5
df.loc[df['dates'].isin(pd.date_range('2018-01-01','2019-01-01'))]
1.53 ms ± 305 µs per loop (mean ± std. dev. of 7 runs, 5 loops each)
Run Code Online (Sandbox Code Playgroud)
但是,它并不比 unutbu 提供的当前接受的答案快,前提是已经创建了掩码。但是如果掩码是动态的并且需要一遍又一遍地重新分配,我的方法可能更有效:
# already create the mask THEN time the function
start_date = dt.datetime(2018,11,27)
end_date = dt.datetime(2019,1,15)
mask = (df['dates'] > start_date) & (df['dates'] <= end_date)
%%timeit -n 5
df.loc[mask]
191 µs ± 28.5 µs per loop (mean ± std. dev. of 7 runs, 5 loops each)
Run Code Online (Sandbox Code Playgroud)
import pandas as pd
technologies = ({
'Courses':["Spark","PySpark","Hadoop","Python","Pandas","Hadoop","Spark"],
'Fee' :[22000,25000,23000,24000,26000,25000,25000],
'Duration':['30days','50days','55days','40days','60days','35days','55days'],
'Discount':[1000,2300,1000,1200,2500,1300,1400],
'InsertedDates':["2021-11-14","2021-11-15","2021-11-16","2021-11-17","2021-11-18","2021-11-19","2021-11-20"]
})
df = pd.DataFrame(technologies)
print(df)
Run Code Online (Sandbox Code Playgroud)
mask = (df['InsertedDates'] > start_date) & (df['InsertedDates'] <= end_date)
df2 = df.loc[mask]
print(df2)
Run Code Online (Sandbox Code Playgroud)
start_date = '2021-11-15'
end_date = '2021-11-19'
after_start_date = df["InsertedDates"] >= start_date
before_end_date = df["InsertedDates"] <= end_date
between_two_dates = after_start_date & before_end_date
df2 = df.loc[between_two_dates]
print(df2)
Run Code Online (Sandbox Code Playgroud)
start_date = '2021-11-15'
end_date = '2021-11-18'
df2 = df.query('InsertedDates >= @start_date and InsertedDates <= @end_date')
print(df2)
Run Code Online (Sandbox Code Playgroud)
start_date = '2021-11-15'
end_date = '2021-11-18'
df2 = df.query('InsertedDates > @start_date and InsertedDates < @end_date')
print(df2)
Run Code Online (Sandbox Code Playgroud)
df2 = df.loc[df["InsertedDates"].between("2021-11-16", "2021-11-18")]
print(df2)
Run Code Online (Sandbox Code Playgroud)
df2 = df[df["InsertedDates"].isin(pd.date_range("2021-11-15", "2021-11-17"))]
print(df2)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
274475 次 |
| 最近记录: |