python - 时间作为 Python 字典的关键

标签 python pandas dictionary

我有一个 CSV 导出,其中的日期/时间以 15 分钟为间隔列出。

时间在导出中显示为以下示例:2019-09-04T02:15:00Z
导入文件后,我将时间 (HH:MM:SS) 分隔到一个新列中。我想添加一个新列,它将为字典中的每 15 分钟间隔分配一个文本字符串(“ON”或“RTH”)。

在 Excel 中执行此操作很简单,但我正在尝试通过 Python 学习如何操作。每次运行此代码时,新列都是空白的(没有错误消息)。我的想法是字典键使用时间有问题。谁能让我知道我错过了什么?

import pandas as pd

# file export from TradingView

df = pd.read_csv(file, sep=',')
df = df.rename(columns={'time': 'Date', 'open': 'Open', 'high': 'High', 'low': 'Low', 'close': 'Close'})


df["Date"] = pd.to_datetime(df["Date"])

df["Time"] = df["Date"].dt.time

# a shortened version of the dictionary for illustration

time_dictionary = {'02:15:00': 'ON', '02:30:00': 'ON', '11:00:00': 'RTH'}

# new column to assign the text strings

df['Session'] = df['Time'].map(time_dictionary)

最佳答案

您正在使用

df["Time"] = df["Date"].dt.time

哪一个

returns numpy array of datetime.time (https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.time.html)




df["Time"] = df["Date"].dt.strftime('%H:%M:%S')

相反,它返回格式化的字符串( https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.strftime.html )。

完整代码:
import pandas as pd

# file export from TradingView

df = pd.read_csv(file, sep=',')
df = df.rename(columns={'time': 'Date', 'open': 'Open', 'high': 'High', 'low': 'Low', 'close': 'Close'})


df["Date"] = pd.to_datetime(df["Date"])

df["Time"] = df["Date"].dt.strftime('%H:%M:%S')

# a shortened version of the dictionary for illustration

time_dictionary = {'02:15:00': 'ON', '02:30:00': 'ON', '11:00:00': 'RTH'}

# new column to assign the text strings

df['Session'] = df['Time'].map(time_dictionary)

关于python - 时间作为 Python 字典的关键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59585715/

相关文章:

python - Statsmodels 中的 ARMA 订单规范

python - 根据现有列中的值计算新列

python - 为什么 sklearn 的 LabelEncoder 应该只用于目标变量?

python - 计算两列中任一列中字符串出现次数的矢量化方法

python - 密文 Letter Freq Substitution : Comparing 2 dictionaries' dict keys by value and altering a text

python - 将字典列表转换为字典

java - 如何将 Map<T,List<L>> 映射中的值添加到 List<L>?

python - 使用 python 从 .gz 文件中删除特定行(模式)以处理大文件

python - 将原始数字写入磁盘

python - 如何使用 pandas 和 yahoo finance 获得 ' USDJPY'(货币汇率)?