Programing

팬더는 열을 색인으로 사용할 수 있습니까?

crosscheck 2020. 10. 14. 07:30
반응형

팬더는 열을 색인으로 사용할 수 있습니까?


다음과 같은 스프레드 시트가 있습니다.

Locality    2005    2006    2007    2008    2009

ABBOTSFORD  427000  448000  602500  600000  638500
ABERFELDIE  534000  600000  735000  710000  775000
AIREYS INLET459000  440000  430000  517500  512500

열을 행과 수동으로 바꾸고 싶지 않습니다. 다음과 같이 목록에 데이터를 읽는 팬더를 사용할 수 있습니까?

data['ABBOTSFORD']=[427000,448000,602500,600000,638500]
data['ABERFELDIE']=[534000,600000,735000,710000,775000]
data['AIREYS INLET']=[459000,440000,430000,517500,512500]

예, set_index를 사용 하면 Locality행 인덱스를 만들 수 있습니다.

data.set_index('Locality', inplace=True)

경우 inplace=True제공되지 않으며, set_index그 결과 수정 된 dataframe를 반환합니다.

예:

> 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]

을 사용하여 이미 설명한대로 색인을 변경할 수 있습니다 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

그런 다음 데이터 프레임 열 값을 가져 와서 목록으로 변환 할 수 있습니다.

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

[427000, 448000]

Pandas의 스프레드 시트에서 읽는 동안 사용 가능한 index_col 매개 변수를 사용 하여 열 색인을 설정할 수 있습니다 .

내 해결책은 다음과 같습니다.

  1. 먼저 pandas를 pd로 가져옵니다. import pandas as pd

  2. Read in filename using pd.read_excel() (if you have your data in a spreadsheet) and set the index to 'Locality' by specifying the index_col parameter.

    df = pd.read_excel('testexcel.xlsx', index_col=0)

    At this stage if you get a 'no module named xlrd' error, install it using pip install xlrd.

  3. For visual inspection, read the dataframe using df.head() which will print the following output sc

  4. Now you can fetch the values of the desired columns of the dataframe and print it

    sc2

참고URL : https://stackoverflow.com/questions/38542419/could-pandas-use-column-as-index

반응형