【问题标题】:How does re-index in Pandas with Series work? [closed]Pandas with Series 中的重新索引如何工作? [关闭]
【发布时间】:2021-06-27 16:26:02
【问题描述】:

我正在研究 Pandas 和 Series,出于教育目的,我创建了这个示例:

s = pd.Series([1, 3, 5, 8, 2], index = ['a', 'b', 'c', 'd', 'e'])
s1 = s1.reindex(['a', 'b', 'e'])
print(s1)

我的输出:

a    1.0
b    NaN
e    NaN
dtype: float64

首先,我不明白为什么“b”和“e”是 NaN,因为源索引列表中有这些索引。另外,我不明白为什么输出系列是浮点数,而不是整数。

【问题讨论】:

  • 看起来s1 是在此之前定义的其他变量,您应该尝试s1 = s.reindex(['a', 'b', 'e'])

标签: pandas series


【解决方案1】:

应该是

s1 = s.reindex(['a', 'b', 'e'])
a    1
b    3
e    2
dtype: int64

或简单的loc

s.loc[['a', 'b', 'e']]
a    1
b    3
e    2
dtype: int64

【讨论】:

  • 这不是错字吗?
【解决方案2】:

似乎s1 是在程序的其他地方定义的变量。您可以改为执行以下操作。

s = pd.Series([1, 3, 5, 8, 2], index = ['a', 'b', 'c', 'd', 'e'])
s1 = s.reindex(['a', 'b', 'e'])
print(s1)

输出是:

a    1
b    3
e    2
dtype: int64

【讨论】:

猜你喜欢
  • 2014-03-24
  • 2016-02-28
  • 2010-09-05
  • 1970-01-01
  • 2020-07-21
  • 1970-01-01
  • 2013-01-07
  • 2023-03-10
  • 1970-01-01
相关资源
最近更新 更多