从数据帧构造序列时缺少第一行

问题描述 投票:1回答:1

我有一本字典,我称之为'test_dict'

test_dict = {'OBJECTID': {0: 1, 1: 2, 2: 3, 3: 4, 4: 5},
'Country': {0: 'Vietnam',
 1: 'Vietnam',
 2: 'Vietnam',
 3: 'Vietnam',
 4: 'Vietnam'},
'Location': {0: 'Nha Trang',
 1: 'Hue',
 2: 'Phu Quoc',
 3: 'Chu Lai',
 4: 'Lao Bao'},
'Lat': {0: 12.250000000000057,
 1: 16.401000000000067,
 2: 10.227000000000032,
 3: 15.406000000000063,
 4: 16.627300000000048},
'Long': {0: 109.18333300000006,
 1: 107.70300000000009,
 2: 103.96700000000004,
 3: 108.70600000000007,
 4: 106.59970000000004}}

我将其转换为DataFrame

test_df = pd.DataFrame(test_dict)

我知道了:

    OBJECTID    Country  Location   Lat      Long
  0   1         Vietnam  Nha Trang  12.2500 109.183333
  1   2         Vietnam   Hue       16.4010 107.703000
  2   3         Vietnam   Phu Quoc  10.2270 103.967000
  3   4         Vietnam   Chu Lai   15.4060 108.706000
  4   5         Vietnam   Lao Bao   16.6273 106.599700

我想用位置名称构建一个序列,我希望“ ObjectID”列成为索引。尝试时,我丢失了第一行。

pd.Series(test_df.Location, index=test_df.OBJECTID)

我明白了:

OBJECTID
  1         Hue
  2    Phu Quoc
  3     Chu Lai
  4     Lao Bao
  5         NaN
 Name: Location, dtype: object

我希望得到的是:

  OBJECTID
  1    Nha Trang
  2    Hue
  3    Phu Quoc
  4    Chu Lai
  5    Lao Bao

我在这里做错了什么?为什么转换为系列的过程会丢失第一行?

python dataframe series
1个回答
1
投票

您可以通过以下方式修正您的代码

pd.Series(test_df.Location.values, index=test_df.OBJECTID)

因为问题在于test_df.Location本身的索引始于0

编辑-我的首选替代品:

test_df.set_index('OBJECTID')['Location']
© www.soinside.com 2019 - 2024. All rights reserved.