Program Club

Pandas 데이터 프레임을 시리즈로 변환

proclub 2020. 11. 27. 21:41
반응형

Pandas 데이터 프레임을 시리즈로 변환


나는 팬더를 처음 접했습니다. 1 행 x 23 열의 팬더 데이터 프레임이 있습니다.

이것을 시리즈로 변환하고 싶습니까? 이 작업을 수행하는 가장 비단뱀적인 방법이 무엇인지 궁금합니다.

나는 시도 pd.Series(myResults)했지만 불평 ValueError: cannot copy sequence with size 23 to array axis with dimension 1합니다. 그것은 수학 용어에서 여전히 "벡터"라는 것을 깨닫기에 충분히 똑똑하지 않습니다.

감사!


그것은 수학 용어에서 여전히 "벡터"라는 것을 깨닫기에 충분히 똑똑하지 않습니다.

차라리 차원의 차이를 인식 할만큼 똑똑하다고 말하십시오. :-)

가장 간단한 방법은를 사용하여 해당 행을 위치별로 선택하는 것 iloc입니다. 그러면 열이 새 인덱스로 포함되고 값이 값으로 포함 된 Series가 제공됩니다.

>>> df = pd.DataFrame([list(range(5))], columns=["a{}".format(i) for i in range(5)])
>>> df
   a0  a1  a2  a3  a4
0   0   1   2   3   4
>>> df.iloc[0]
a0    0
a1    1
a2    2
a3    3
a4    4
Name: 0, dtype: int64
>>> type(_)
<class 'pandas.core.series.Series'>

단일 행 데이터 프레임 (여전히 데이터 프레임이 생성됨)을 전치 한 다음 결과를 시리즈로 압축 할 수 있습니다 (의 역 to_frame).

df = pd.DataFrame([list(range(5))], columns=["a{}".format(i) for i in range(5)])

>>> df.T.squeeze()  # Or more simply, df.squeeze() for a single row dataframe.
a0    0
a1    1
a2    2
a3    3
a4    4
Name: 0, dtype: int64

참고 : @IanS가 제기 한 포인트를 수용하려면 (OP의 질문에 포함되지 않더라도) 데이터 프레임의 크기를 테스트하십시오. 나는 그것이 df데이터 프레임 이라고 가정하고 있지만 가장자리 케이스는 빈 데이터 프레임, 모양 (1, 1)의 데이터 프레임 및 원하는 기능을 구현 해야하는 두 개 이상의 행이있는 데이터 프레임입니다.

if df.empty:
    # Empty dataframe, so convert to empty Series.
    result = pd.Series()
elif df.shape == (1, 1)
    # DataFrame with one value, so convert to series with appropriate index.
    result = pd.Series(df.iat[0, 0], index=df.columns)
elif len(df) == 1:
    # Convert to series per OP's question.
    result = df.T.squeeze()
else:
    # Dataframe with multiple rows.  Implement desired behavior.
    pass

이것은 @themachinist가 제공하는 답변 라인을 따라 단순화 할 수도 있습니다.

if len(df) > 1:
    # Dataframe with multiple rows.  Implement desired behavior.
    pass
else:
    result = pd.Series() if df.empty else df.iloc[0, :]

다음 두 가지 방법 중 하나를 사용하여 데이터 프레임을 분할하여 시리즈를 검색 할 수 있습니다.

http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iloc.html http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html

import pandas as pd
import numpy as np
df = pd.DataFrame(data=np.random.randn(1,8))

series1=df.iloc[0,:]
type(series1)
pandas.core.series.Series

Another way -

Suppose myResult is the dataFrame that contains your data in the form of 1 col and 23 rows

// label your columns by passing a list of names
myResult.columns = ['firstCol']

// fetch the column in this way, which will return you a series
myResult = myResult['firstCol']

print(type(myResult))

In similar fashion, you can get series from Dataframe with multiple columns.

참고URL : https://stackoverflow.com/questions/33246771/convert-pandas-data-frame-to-series

반응형