gpt4 book ai didi

python - 为什么重新索引后会显示 nan 值?

转载 作者:行者123 更新时间:2023-12-02 02:01:57 25 4
gpt4 key购买 nike

我正在尝试重新索引列,但它显示的是 nan 值。我不明白为什么?

data = {
"age": [50, 40, 30, 40],
"qualified": [True, False, False, False]
}
index = ["P", "Q", "R", "S"]
df = pd.DataFrame(data, index=index)

new = ["A", "B", "C", "D"]
newdf = df.reindex(new)
print(newdf)

输出:

   age qualified
A NaN NaN
B NaN NaN
C NaN NaN
D NaN NaN

最佳答案

我认为你需要DataFrame.set_index ,如果需要用新值替换索引值,则使用嵌套列表:

new = ["A", "B", "C", "D"]
newdf = df.set_index([new])
#alternative
#newdf.index = new
print(newdf)
age qualified
A 50 True
B 40 False
C 30 False
D 40 False

方法DataFrame.reindex工作方式不同 - 它通过带有对齐数据的列表创建新索引 - 这意味着首先通过新列表 new 的值匹配索引的现有值,对于不匹配的值创建 NaN:

data = {
"age": [50, 40, 30, 40],
"qualified": [True, False, False, False]
}
index = ["A", "Q", "D", "C"]
df = pd.DataFrame(data, index=index)

new = ["A", "B", "C"]
newdf = df.reindex(new)
print(newdf)

age qualified
A 50.0 True
B NaN NaN
C 40.0 False

关于python - 为什么重新索引后会显示 nan 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68917439/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com