【问题标题】:Pandas DataFrame constructor introduces NaN when including the index argumentPandas DataFrame 构造函数在包含索引参数时引入 NaN
【发布时间】:2014-11-28 17:02:04
【问题描述】:

我正在使用 DataFrame 构造函数创建一个 pandas DataFrame 对象。我的数据是列表和分类数据系列对象的字典。当我将索引传递给构造函数时,我的分类数据系列将被重置为 NaN 值。这里发生了什么?提前致谢!

例子:

import pandas as pd
import numpy as np
a = pd.Series(['a','b','c'],dtype="category")
b = pd.Series(['a','b','c'],dtype="object")
c = pd.Series(['a','b','cc'],dtype="object")

A = pd.DataFrame({'A':a,'B':[1,2,3]},index=["0","1","2"])
AA = pd.DataFrame({'A':a,'B':[1,2,3]})
B = pd.DataFrame({'A':b,'C':[4,5,6]})    

print("DF A:")
print(A)
print("\nDF A, without specifying an index in the constructor:")
print(AA)
print("\nDF B:")
print(B)

【问题讨论】:

标签: python pandas


【解决方案1】:

这与类别与对象没有任何关系,它与索引对齐有关。

你在 A 中得到了 NaN,因为你告诉构造函数你想要三个字符串的索引。但是a 有自己的索引,由整数[0, 1, 2] 组成。由于这与您说想要的索引不匹配,因此数据不会对齐,因此您会得到一个带有您说想要的索引的 DataFrame,并且 NaN 突出显示数据丢失。相比之下,B 只是一个列表,因此没有可忽略的索引,因此它假定数据以适合索引的顺序给出。

这可能比解释更容易看到。不管 dtype 是什么,如果索引不匹配,你会得到 NaN:

In [147]: pd.DataFrame({'A':pd.Series(list("abc"), dtype="category"),'B':[1,2,3]},
          index=["0","1","2"])
Out[147]: 
     A  B
0  NaN  1
1  NaN  2
2  NaN  3

In [148]: pd.DataFrame({'A':pd.Series(list("abc"), dtype="object"),'B':[1,2,3]},
          index=["0","1","2"])
Out[148]: 
     A  B
0  NaN  1
1  NaN  2
2  NaN  3

如果你使用完全匹配的索引,它可以工作:

In [149]: pd.DataFrame({'A':pd.Series(list("abc"), dtype="object"),'B':[1,2,3]},
          index=[0,1,2])
Out[149]: 
   A  B
0  a  1
1  b  2
2  c  3

如果您使用部分匹配的索引,您将获得索引对齐的值和不对齐的 NaN:

In [150]: pd.DataFrame({'A':pd.Series(list("abc"), dtype="object"),'B':[1,2,3]},
          index=[0,1,10])
Out[150]: 
      A  B
0     a  1
1     b  2
10  NaN  3

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-30
    • 1970-01-01
    • 2020-05-11
    • 1970-01-01
    • 2021-10-30
    • 2016-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多