【问题标题】:For some reason, the fordoes not work properly由于某种原因,fordo 无法正常工作
【发布时间】:2021-03-09 13:23:11
【问题描述】:

How to output to dict type in Pandas

刚刚在这里问了一个问题,稍微了解了一下问题的原因,但是不知道怎么解决,所以问了。

这是数据最初显示的内容。

"report": {
    "2020-3-27": 999,
    "2021-2-18": 1221,
    "2021-2-22": 1201,
    "2021-3-2": 1004,
    "2021-3-3": 491,
    "2021-3-5": 168
},

以前的数据分为日期和数据部分,缺的部分补上。

mappedData = {
            f"{record['created_at__year']}-{record['created_at__month']}-{record['created_at__day']}":
            record['time__sum']
            for record in data
}

s = pd.Series(mappedData)
idx = pd.date_range(s.index.min(), s.index.max())
s.index = pd.DatetimeIndex(s.index)
s = s.reindex(idx, fill_value=0)

s

"report": [
            999,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            ......
]

s.index

"report": [
            "2020-03-27T00:00:00",
            "2020-03-28T00:00:00",
            "2020-03-29T00:00:00",
            "2020-03-30T00:00:00",
            "2020-03-31T00:00:00",
            "2020-04-01T00:00:00",
            "2020-04-02T00:00:00",
            "2020-04-03T00:00:00",
            .....
]
test = {s.index[i]: s[i] for i in range(len(s))}

我希望 statemenet 的结果看起来像这样

"report": [
            "2020-03-27T00:00:00":999,
            "2020-03-28T00:00:00":0,
            "2020-03-29T00:00:00":0,
            "2020-03-30T00:00:00":0,
            "2020-03-31T00:00:00":0,
            "2020-04-01T00:00:00":0,
            "2020-04-02T00:00:00":0,
            "2020-04-03T00:00:00":0,
            .....
]

如果你运行之前的代码,你会得到错误信息“keys must be str, int, float, bool or None, not int64”。

如果我用test = {s[i] for i in range(len(s))}test = {s.index[i] for i in range(len(s))} 尝试它,它可以工作,但如果我用test = {s[i] for i in range(len(s))} 尝试它,它就不起作用。修复第一个缺失数据的结果不反映,返回后面的数据。

我认为错误“keys must be str, int, float, bool or None, not int64”是由ss.index的数量不同引起的。它是否正确? 它是否正确?还有,我该如何改进呢?

对不起,我是初学者,但如果你能告诉我,我将不胜感激。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    如果我理解正确,您想从您的系列中获取字典。 嗯,有这个pd.Series.to_dict()的函数

    test = s.to_dict()
    

    如果你真的想遍历系列,那么我会使用enumerate() 而不是range(len(s))

    test = {s.index[i]:v for i, v in enumerate(s)}
    

    【讨论】:

    • 感谢您的回答!我不想从系列中提取字典,我想创建一个像 { s : s.index } 这样的字典类型。但是{s[i]: s.index[i] for i in range(len(s))} 效果不好。
    猜你喜欢
    • 2013-12-28
    • 1970-01-01
    • 2016-12-06
    • 2012-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-07
    • 2022-01-20
    相关资源
    最近更新 更多