
在pandas中处理时间序列数据时,一项常见任务是根据特定的日期或日期时间条件,从dataframe中提取相应的列值,并将不符合条件的行填充为nan(not a number)。例如,你可能只想在某个特定交易日记录“事件”值,而在其他日期则标记为缺失。
初学者在尝试解决此类问题时,可能会倾向于使用for循环遍历DataFrame的行,但这种方法通常效率低下,并且容易因不当的赋值操作导致错误结果。本教程将深入探讨如何使用Pandas的向量化操作,以高效、简洁且正确的方式实现这一目标。
Series.where()是Pandas中一个非常强大的方法,它允许你根据一个布尔条件选择性地保留或替换Series中的值。当条件为True时,保留原始值;当条件为False时,则替换为指定值(默认为NaN)。这是处理条件赋值任务的首选方法,因为它利用了Pandas底层的优化,效率远高于Python循环。
如果你的DataFrame索引包含时间信息(例如,每小时、每分钟),但你只想根据日期进行匹配(即,某天的所有时间点都符合条件),可以使用DatetimeIndex.normalize()方法。normalize()会将所有日期时间戳规范化为当天的午夜(00:00:00),从而方便进行日期层面的比较。
示例代码:
import pandas as pd
import numpy as np
# 创建一个带有时间组件的示例DataFrame
rng_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 (带时间组件):
close
2000-03-19 00:00:00 0
2000-03-19 09:00:00 1
2000-03-19 18:00:00 2
2000-03-20 03:00:00 3
2000-03-20 12:00:00 4
2000-03-20 21:00:00 5
2000-03-21 06:00:00 6
2000-03-21 15:00:00 7
2000-03-22 00:00:00 8
2000-03-22 09:00:00 9
------------------------------
使用 normalize() 提取 '2000-03-20' 的 'event' 列:
close event
2000-03-19 00:00:00 0 NaN
2000-03-19 09:00:00 1 NaN
2000-03-19 18:00:00 2 NaN
2000-03-20 03:00:00 3 3.0
2000-03-20 12:00:00 4 4.0
2000-03-20 21:00:00 5 5.0
2000-03-21 06:00:00 6 NaN
2000-03-21 15:00:00 7 NaN
2000-03-22 00:00:00 8 NaN
2000-03-22 09:00:00 9 NaN如果你的DataFrame索引没有时间组件(例如,每日数据),或者你需要精确匹配到特定的日期和时间点,可以直接将DataFrame索引与目标pd.Timestamp对象或日期时间字符串进行比较。
示例代码:
import pandas as pd
import 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 (每日数据):
close
2000-03-19 0
2000-03-20 1
2000-03-21 2
2000-03-22 3
2000-03-23 4
2000-03-24 5
2000-03-25 6
2000-03-26 7
2000-03-27 8
2000-03-28 9
------------------------------
使用 Series.where() 精确匹配 '2000-03-20' 的 'event' 列:
close event
2000-03-19 0 NaN
2000-03-20 1 1.0
2000-03-21 2 NaN
2000-03-22 3 NaN
2000-03-23 4 NaN
2000-03-24 5 NaN
2000-03-25 6 NaN
2000-03-26 7 NaN
2000-03-27 8 NaN
2000-03-28 9 NaNPandas的DatetimeIndex支持强大的部分字符串索引功能。这意味着你可以使用日期字符串(例如'YYYY-MM-DD')直接选择该日期内的所有行。结合loc方法,这提供了一种简洁的方式来更新或赋值特定日期的列值。
要实现“仅在特定日期有值,其他日期为NaN”的效果,可以先将目标列初始化为NaN,然后使用部分字符串索引对特定日期进行赋值。
示例代码:
import pandas as pd
import numpy as np
# 使用带有时间组件的DataFrame
rng_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' 列为 NaN
df_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 (用于部分字符串索引):
close
2000-03-19 00:00:00 0
2000-03-19 09:00:00 1
2000-03-19 18:00:00 2
2000-03-20 03:00:00 3
2000-03-20 12:00:00 4
2000-03-20 21:00:00 5
2000-03-21 06:00:00 6
2000-03-21 15:00:00 7
2000-03-22 00:00:00 8
2000-03-22 09:00:00 9
------------------------------
使用部分字符串索引提取 '2000-03-20' 的 'event' 列:
close event
2000-03-19 00:00:00 0 NaN
2000-03-19 09:00:00 1 NaN
2000-03-19 18:00:00 2 NaN
2000-03-20 03:00:00 3 3.0
2000-03-20 12:00:00 4 4.0
2000-03-20 21:00:00 5 5.0
2000-03-21 06:00:00 6 NaN
2000-03-21 15:00:00 7 NaN
2000-03-22 00:00:00 8 NaN
2000-03-22 09:00:00 9 NaN虽然iterrows循环在某些复杂场景下可能有用,但它通常不是处理DataFrame的推荐方式,尤其是在需要更新DataFrame时。原始问题中遇到的错误就是df['event'] = row['close']在每次循环中都会尝试将整个event列赋值为当前行的close值,而不是只更新当前行。这导致最终event列被最后一次迭代的值(或NaN)覆盖。
要正确地在循环中更新DataFrame,必须使用df.loc或df.iloc进行基于标签或整数位置的赋值。
修正后的 iterrows 循环示例:
import pandas as pd
import numpy as np
# 使用带有时间组件的DataFrame
rng_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.nan
print("\n修正后的 iterrows 循环 (精确按日期时间匹配):")
print(df_daily_loop)输出:
原始DataFrame (用于修正循环):
close
2000-03-19 00:00:00 0
2000-03-19 09:00:00 1
2000-03-19 18:00:00 2
2000-03-20 03:00:00 以上就是Pandas教程:使用向量化方法按日期筛选DataFrame列值的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号