python - 给定 DatetimeIndex 和日期时间感知记录的集合,如何创建 Pandas DataFrame?

标签 python pandas dataframe

我有一个预定义的 DatetimeIndex 和一个此类元组列表:(datetime、float、float、float)。我需要创建一个 Pandas DataFrame 并用列表中的数据填充它。不用说,每个记录的第一个元素(一个元组)定义了它在生成的 DataFrame 中的假定位置,而不是列的值,生成的 DataFrame 中只有 3 个浮点列。在 DatetimeIndex 中没有匹配元素的记录应该被丢弃(并且我不介意在这种情况下出现错误)。

给定元组本身的列表pd.DataFrame.from_records()将元组的每个元素视为列的值(如果我不包含日期时间列,则会引发错误在列列表中)。

给定一个定义为 {r[0]: (r[1], r[2], r[3]) for r in rs} 的字典(其中 rs 是元组的源列表)pd.DataFrame.from_records() 返回一个 DataFrame,其中每列的每个字段中的每个值都是 NaN。我还尝试使用列表而不是元组 ({r[0]: [r[1], r[2], r[3]] for r in rs}) 但结果是相同。我已经仔细检查过 - 源元组中的值几乎都是定义的 float ,并且没有 NaN 或 None。设置 coerce_float 不会改变任何内容。

更新:我还尝试使用字典字典根据列列表指定列名称 ({r[0]: {'A': r[1], 'B': r[ 2], 'C': r[3]} for r in rs}),结果是相同的 - 都是 NaN。

更新:这里有一个例子:

dts = [
    datetime(2018, 1, 1, 0, 0, 0, 0, timezone.utc),
    datetime(2018, 1, 2, 0, 0, 0, 0, timezone.utc),
    datetime(2018, 1, 3, 0, 0, 0, 0, timezone.utc)
]

dti = pd.DatetimeIndex(dts, tz=timezone.utc)

rs = [
    (datetime(2018, 1, 1, 0, 0, 0, 0, timezone.utc), 0.1, 0.2, 0.3),
    (datetime(2018, 1, 2, 0, 0, 0, 0, timezone.utc), 0.4, 0.5, 0.6),
    (datetime(2018, 1, 3, 0, 0, 0, 0, timezone.utc), 0.7, 0.8, 0.9)
]

# ...

dtf = pd.DataFrame.from_records(rs, index=dti, columns=['A', 'B', 'C'], coerce_float=True)

print(dtf)

应该导致

                           A    B    C  
2008-01-01 00:00:00+00:00  0.1  0.2  0.3
2008-01-02 00:00:00+00:00  0.3  0.5  0.6
2008-01-03 00:00:00+00:00  0.7  0.8  0.9

但如果以这种方式运行,它实际上会导致 AssertionError: 3 columns Passed, Passed data had 4 columns。我应该写什么来代替 # ...?或者,也许我应该使用什么来代替 from_records 来在给定输入的情况下达到所需的结果?

最佳答案

假设您给定的日期时间索引名为 dti,只需使用元组列表创建数据框,将索引设置为第一个日期时间列,然后重新索引为 dti:

df = pd.DataFrame(rs, columns=['datetime', 'A', 'B', 'C'])
>>> df.set_index('datetime').reindex(dti)
              A    B    C
2018-01-01  0.1  0.2  0.3
2018-01-02  0.3  0.5  0.6
2018-01-03  0.7  0.8  0.9

关于python - 给定 DatetimeIndex 和日期时间感知记录的集合,如何创建 Pandas DataFrame?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52712386/

相关文章:

python - 如何在 Pandas 中用滚动平均值填充南值

r - 如何从多个数据帧创建热图

python - Python中浮点格式转换为年月格式

python - 在 python 2.7 上使用 pandas

python - 不能有多个具有相同选择的模型字段

python - 通过理解简化嵌套的 for 循环

python - 如何将 scipy.stats.describe 应用于每个组?

python - Pandas - 如何在函数中传递列名称

python - 合并数据框中的值以在 excel 中写入

python - 使用 python 套接字发送/接收数据