
在pandas中处理时间序列数据时,一项常见任务是根据特定的日期或日期时间条件,从dataframe中提取相应的列值,并将不符合条件的行填充为nan(not a number)。例如,你可能只想在某个特定交易日记录“事件”值,而在其他日期则标记为缺失。
初学者在尝试解决此类问题时,可能会倾向于使用for循环遍历DataFrame的行,但这种方法通常效率低下,并且容易因不当的赋值操作导致错误结果。本教程将深入探讨如何使用Pandas的向量化操作,以高效、简洁且正确的方式实现这一目标。
1. 向量化操作:使用 Series.where() (推荐)
Series.where()是Pandas中一个非常强大的方法,它允许你根据一个布尔条件选择性地保留或替换Series中的值。当条件为True时,保留原始值;当条件为False时,则替换为指定值(默认为NaN)。这是处理条件赋值任务的首选方法,因为它利用了Pandas底层的优化,效率远高于Python循环。
1.1 场景一:仅按日期匹配(忽略时间部分)
如果你的DataFrame索引包含时间信息(例如,每小时、每分钟),但你只想根据日期进行匹配(即,某天的所有时间点都符合条件),可以使用DatetimeIndex.normalize()方法。normalize()会将所有日期时间戳规范化为当天的午夜(00:00:00),从而方便进行日期层面的比较。
示例代码:
import pandas as pdimport numpy as np# 创建一个带有时间组件的示例DataFramerng_with_time = pd.date_range('2000-03-19', periods=10, freq='9H')df_with_time = pd.DataFrame({'close': range(10)}, index=rng_with_time)print("原始DataFrame (带时间组件):")print(df_with_time)print("-" * 30)# 使用 Series.where() 和 normalize() 提取特定日期的 'close' 值# 目标日期为 '2000-03-20'df_with_time['event'] = df_with_time['close'].where( df_with_time.index.normalize() == pd.Timestamp('2000-03-20'))print("n使用 normalize() 提取 '2000-03-20' 的 'event' 列:")print(df_with_time)
输出:
原始DataFrame (带时间组件): close2000-03-19 00:00:00 02000-03-19 09:00:00 12000-03-19 18:00:00 22000-03-20 03:00:00 32000-03-20 12:00:00 42000-03-20 21:00:00 52000-03-21 06:00:00 62000-03-21 15:00:00 72000-03-22 00:00:00 82000-03-22 09:00:00 9------------------------------使用 normalize() 提取 '2000-03-20' 的 'event' 列: close event2000-03-19 00:00:00 0 NaN2000-03-19 09:00:00 1 NaN2000-03-19 18:00:00 2 NaN2000-03-20 03:00:00 3 3.02000-03-20 12:00:00 4 4.02000-03-20 21:00:00 5 5.02000-03-21 06:00:00 6 NaN2000-03-21 15:00:00 7 NaN2000-03-22 00:00:00 8 NaN2000-03-22 09:00:00 9 NaN
1.2 场景二:精确按日期时间匹配
如果你的DataFrame索引没有时间组件(例如,每日数据),或者你需要精确匹配到特定的日期和时间点,可以直接将DataFrame索引与目标pd.Timestamp对象或日期时间字符串进行比较。
示例代码:
import pandas as pdimport numpy as np# 创建一个不带时间组件的示例DataFrame (每日数据)rng_daily = pd.date_range('2000-03-19', periods=10)df_daily = pd.DataFrame({'close': range(10)}, index=rng_daily)print("原始DataFrame (每日数据):")print(df_daily)print("-" * 30)# 使用 Series.where() 精确匹配 '2000-03-20 00:00:00'df_daily['event'] = df_daily['close'].where( df_daily.index == pd.Timestamp('2000-03-20 00:00:00'))print("n使用 Series.where() 精确匹配 '2000-03-20' 的 'event' 列:")print(df_daily)
输出:
原始DataFrame (每日数据): close2000-03-19 02000-03-20 12000-03-21 22000-03-22 32000-03-23 42000-03-24 52000-03-25 62000-03-26 72000-03-27 82000-03-28 9------------------------------使用 Series.where() 精确匹配 '2000-03-20' 的 'event' 列: close event2000-03-19 0 NaN2000-03-20 1 1.02000-03-21 2 NaN2000-03-22 3 NaN2000-03-23 4 NaN2000-03-24 5 NaN2000-03-25 6 NaN2000-03-26 7 NaN2000-03-27 8 NaN2000-03-28 9 NaN
2. 使用部分字符串索引 (Partial String Indexing)
Pandas的DatetimeIndex支持强大的部分字符串索引功能。这意味着你可以使用日期字符串(例如’YYYY-MM-DD’)直接选择该日期内的所有行。结合loc方法,这提供了一种简洁的方式来更新或赋值特定日期的列值。
ProWritingAid
AI写作助手软件
114 查看详情
要实现“仅在特定日期有值,其他日期为NaN”的效果,可以先将目标列初始化为NaN,然后使用部分字符串索引对特定日期进行赋值。
示例代码:
import pandas as pdimport numpy as np# 使用带有时间组件的DataFramerng_with_time = pd.date_range('2000-03-19', periods=10, freq='9H')df_with_time_psi = pd.DataFrame({'close': range(10)}, index=rng_with_time)print("原始DataFrame (用于部分字符串索引):")print(df_with_time_psi)print("-" * 30)# 初始化 'event' 列为 NaNdf_with_time_psi['event'] = np.nan# 使用部分字符串索引将 '2000-03-20' 的 'close' 值赋给 'event' 列df_with_time_psi.loc['2000-03-20', 'event'] = df_with_time_psi['close']print("n使用部分字符串索引提取 '2000-03-20' 的 'event' 列:")print(df_with_time_psi)
输出:
原始DataFrame (用于部分字符串索引): close2000-03-19 00:00:00 02000-03-19 09:00:00 12000-03-19 18:00:00 22000-03-20 03:00:00 32000-03-20 12:00:00 42000-03-20 21:00:00 52000-03-21 06:00:00 62000-03-21 15:00:00 72000-03-22 00:00:00 82000-03-22 09:00:00 9------------------------------使用部分字符串索引提取 '2000-03-20' 的 'event' 列: close event2000-03-19 00:00:00 0 NaN2000-03-19 09:00:00 1 NaN2000-03-19 18:00:00 2 NaN2000-03-20 03:00:00 3 3.02000-03-20 12:00:00 4 4.02000-03-20 21:00:00 5 5.02000-03-21 06:00:00 6 NaN2000-03-21 15:00:00 7 NaN2000-03-22 00:00:00 8 NaN2000-03-22 09:00:00 9 NaN
3. 修正 iterrows 循环(不推荐)
虽然iterrows循环在某些复杂场景下可能有用,但它通常不是处理DataFrame的推荐方式,尤其是在需要更新DataFrame时。原始问题中遇到的错误就是df[‘event’] = row[‘close’]在每次循环中都会尝试将整个event列赋值为当前行的close值,而不是只更新当前行。这导致最终event列被最后一次迭代的值(或NaN)覆盖。
要正确地在循环中更新DataFrame,必须使用df.loc或df.iloc进行基于标签或整数位置的赋值。
修正后的 iterrows 循环示例:
import pandas as pdimport numpy as np# 使用带有时间组件的DataFramerng_with_time_loop = pd.date_range('2000-03-19', periods=10, freq='9H')df_with_time_loop = pd.DataFrame({'close': range(10)}, index=rng_with_time_loop)print("原始DataFrame (用于修正循环):")print(df_with_time_loop)print("-" * 30)# 初始化 'event' 列为 NaN,这是在循环前应该做的df_with_time_loop['event'] = np.nan# 修正后的 iterrows 循环,按日期匹配for index, row in df_with_time_loop.iterrows(): # 使用 normalize() 仅比较日期部分 if index.normalize() == pd.Timestamp('2000-03-20 00:00:00'): df_with_time_loop.loc[index, 'event'] = row['close'] else: df_with_time_loop.loc[index, 'event'] = np.nan # 明确设置为 NaN,虽然已经初始化print("n修正后的 iterrows 循环 (按日期匹配):")print(df_with_time_loop)# ----------------------------------------------------# 使用不带时间组件的DataFrame (每日数据)rng_daily_loop = pd.date_range('2000-03-19', periods=10)df_daily_loop = pd.DataFrame({'close': range(10)}, index=rng_daily_loop)print("n" + "=" * 30)print("原始DataFrame (每日数据,用于修正循环):")print(df_daily_loop)print("-" * 30)df_daily_loop['event'] = np.nan# 修正后的 iterrows 循环,精确按日期时间匹配for index, row in df_daily_loop.iterrows(): # 精确匹配日期时间 if index == pd.Timestamp('2000-03-20 00:00:00'): df_daily_loop.loc[index, 'event'] = row['close'] else: df_daily_loop.loc[index, 'event'] = np.nanprint("n修正后的 iterrows 循环 (精确按日期时间匹配):")print(df_daily_loop)
输出:
原始DataFrame (用于修正循环): close2000-03-19 00:00:00 02000-03-19 09:00:00 12000-03-19 18:00:00 22000-03-20 03:00:00
以上就是Pandas教程:使用向量化方法按日期筛选DataFrame列值的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/918827.html
微信扫一扫
支付宝扫一扫