pandas可以使用列作为索引吗?

Cha*_*tin 80 python excel pandas

我有一个这样的电子表格:

Locality    2005    2006    2007    2008    2009

ABBOTSFORD  427000  448000  602500  600000  638500
ABERFELDIE  534000  600000  735000  710000  775000
AIREYS INLET459000  440000  430000  517500  512500
Run Code Online (Sandbox Code Playgroud)

我不想手动将列与行交换.是否可以使用pandas将数据读取到列表中:

data['ABBOTSFORD']=[427000,448000,602500,600000,638500]
data['ABERFELDIE']=[534000,600000,735000,710000,775000]
data['AIREYS INLET']=[459000,440000,430000,517500,512500]
Run Code Online (Sandbox Code Playgroud)

Mic*_*off 163

是的,使用set_index,您可以创建Locality行索引.

data.set_index('Locality', inplace=True)
Run Code Online (Sandbox Code Playgroud)

如果inplace=True未提供,则set_index返回修改后的数据帧.

例:

> import pandas as pd
> df = pd.DataFrame([['ABBOTSFORD', 427000, 448000],
                     ['ABERFELDIE', 534000, 600000]],
                    columns=['Locality', 2005, 2006])

> df
     Locality    2005    2006
0  ABBOTSFORD  427000  448000
1  ABERFELDIE  534000  600000

> df.set_index('Locality', inplace=True)
> df
              2005    2006
Locality                  
ABBOTSFORD  427000  448000
ABERFELDIE  534000  600000

> df.loc['ABBOTSFORD']
2005    427000
2006    448000
Name: ABBOTSFORD, dtype: int64

> df.loc['ABBOTSFORD'][2005]
427000

> df.loc['ABBOTSFORD'].values
array([427000, 448000])

> df.loc['ABBOTSFORD'].tolist()
[427000, 448000]
Run Code Online (Sandbox Code Playgroud)


fam*_*gar 12

您可以按照已使用的说明更改索引set_index.您不需要手动将行与列交换data.T,pandas中有一个transpose()方法可以为您完成:

> df = pd.DataFrame([['ABBOTSFORD', 427000, 448000],
                    ['ABERFELDIE', 534000, 600000]],
                    columns=['Locality', 2005, 2006])

> newdf = df.set_index('Locality').T
> newdf

Locality    ABBOTSFORD  ABERFELDIE
2005        427000      534000
2006        448000      600000
Run Code Online (Sandbox Code Playgroud)

然后,您可以获取dataframe列值并将其转换为列表:

> newdf['ABBOTSFORD'].values.tolist()

[427000, 448000]
Run Code Online (Sandbox Code Playgroud)


the*_*guy 7

另一种简单的方法是将列分配给数据框索引

data = {
  'Locality': ['ABBOTSFORD', 'ABERFELDIE', 'AIREYS INLET'],
  '2005': [427000, 534000, 459000 ],
  '2006': [448000, 448000, 448000],
  '2007': [602500, 602500, 602500],
  '2008': [600000, 710000, 517500],
  '2009': [638500, 775000, 512500]
}

df = pd.DataFrame(data)

# set the locality column as the index
df.index = df['Locality']
Run Code Online (Sandbox Code Playgroud)

如果您不再需要“位置”列作为列,则可以将其删除

df.drop('Locality', axis=1)
Run Code Online (Sandbox Code Playgroud)

你最终会得到


              | 2005     | 2006   | 2007   | 2008   | 2009
Locality      |-------------------------------------------              
ABBOTSFORD    | 427000   | 448000 | 602500 | 600000 | 638500
ABERFELDIE    | 534000   | 448000 | 602500 | 710000 | 775000
AIREYS INLET  | 459000   | 448000 | 602500 | 517500 | 512500
Run Code Online (Sandbox Code Playgroud)