【问题标题】:Values turn to Nan when indexing the keys in a dictionary in Pandas在 Pandas 中索引字典中的键时,值变为 Nan
【发布时间】:2022-08-22 08:26:32
【问题描述】:

我正在努力成为一名自学成才的数据分析师。 在 Pandas 中,当我在代码的第二部分索引不同的名称时,值从 450 变为 Nan,从 500 变为 Nan,380 变为 380.0(浮点数)。 此外,dtype 从 int64 变为 float64。 任何想法为什么会发生这种情况? 此外,如果我从 w3schools 复制一个示例,它是否显示正常。

import numpy as np
import pandas as pd


calories= {\"Day 1\": 450, \"Day 2\": 500, \"day 3\": 380}
new_series= pd.Series(calories)
print(new_series)

**#Second part of code**
new_series_1= pd.Series(calories, index=[\"day 1\", \"day 2\", \"day 3\"])
print(new_series_1)

    标签: python pandas pycharm


    【解决方案1】:

    我试过你的代码。这是一个简单的修复。 Python 和很多程序一样是区分大小写的。你只需要修改你的陈述。

    更改自:

    new_series_1= pd.Series(calories, index=["day 1", "day 2", "day 3"])
    

    至:

    new_series_1= pd.Series(calories, index=["Day 1", "Day 2", "day 3"])
    

    注意大写字母。

    当我确保列名匹配时,我得到了类似的输出。

    Day 1    450
    Day 2    500
    day 3    380
    dtype: int64
    Day 1    450
    Day 2    500
    day 3    380
    dtype: int64
    

    希望有帮助。

    问候。

    【讨论】:

    • 这是我与堆栈溢出的第一次交互,我真的很感谢你的帮助!非常感谢,我现在心里清楚了!!
    【解决方案2】:

    tl;博士

    new_series_1 中,calories 键与index 值不匹配,并且系列正在使用后者重新索引,因此NaNfloat64

    解释

    首先你用calories初始化new_series,这是一个dictint值:

    calories= {"Day 1": 450, "Day 2": 500, "day 3": 380}
    new_series= pd.Series(calories)
    

    所以 Pandas 知道他们可以被最好地对待为int64

    然后在索引中设置 2 个不同的值,day 1day 2,没有大写:

    new_series_1= pd.Series(calories, index=["day 1", "day 2", "day 3"])
    

    calories 的键和 index 值之间不再有对应关系,因此 Pandas 默认为 float64 以进行最佳猜测。 事实上,docs 中的一个示例表明:

    从具有指定索引的字典构造系列

    d = {'a': 1, 'b': 2, 'c': 3}
    ser = pd.Series(data=d, index=['a', 'b', 'c'])
    ser
    a   1
    b   2
    c   3
    dtype: int64
    

    字典的键与索引值匹配,因此索引值无效。

    d = {'a': 1, 'b': 2, 'c': 3}
    ser = pd.Series(data=d, index=['x', 'y', 'z'])
    ser
    x   NaN
    y   NaN
    z   NaN
    dtype: float64
    

    请注意,索引首先使用字典中的键构建。在此之后,系列使用给定的索引值重新索引,因此 结果我们得到了所有的 NaN.

    here 它解释了它何时更改 dtype,基于 Index

    如果 dtype 为 None,我们会找到最适合数据的 dtype。如果 提供了实际的 dtype,如果它是安全的,我们会强制使用该 dtype。 否则,将引发错误。

    【讨论】:

    • 非常感谢我的朋友。感谢您的帮助和您的时间!!你让我完全理解并在我脑海中说清楚!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-20
    • 1970-01-01
    • 2016-02-11
    • 1970-01-01
    • 2017-04-30
    • 1970-01-01
    相关资源
    最近更新 更多