팬더는 열을 색인으로 사용할 수 있습니까?
다음과 같은 스프레드 시트가 있습니다.
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 매개 변수를 사용 하여 열 색인을 설정할 수 있습니다 .
내 해결책은 다음과 같습니다.
먼저 pandas를 pd로 가져옵니다.
import pandas as pd
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
.For visual inspection, read the dataframe using
df.head()
which will print the following outputNow you can fetch the values of the desired columns of the dataframe and print it
참고URL : https://stackoverflow.com/questions/38542419/could-pandas-use-column-as-index
'Programing' 카테고리의 다른 글
테이블 구조 설명 (0) | 2020.10.14 |
---|---|
GOBIN이 설정되지 않았습니다. go install을 실행할 수 없습니다. (0) | 2020.10.14 |
클로저를 설명 할 수 있습니까 (파이썬과 관련이 있기 때문에)? (0) | 2020.10.14 |
SQL Server 2008 백업 오류-운영 체제 오류 5 (이 오류에 대한 텍스트를 검색하지 못했습니다. 이유 : 15105) (0) | 2020.10.14 |
Linux C 프로그램에서 pthread의 스레드 ID를 얻는 방법은 무엇입니까? (0) | 2020.10.14 |