programing tip

목록 목록에 Pandas DataFrame

itbloger 2020. 10. 10. 09:41
반응형

목록 목록에 Pandas DataFrame


목록 목록을 pandas 데이터 프레임으로 바꾸는 것은 쉽습니다.

import pandas as pd
df = pd.DataFrame([[1,2,3],[3,4,5]])

하지만 df를 목록 목록으로 되돌리려면 어떻게해야합니까?

lol = df.what_to_do_now?
print lol
# [[1,2,3],[3,4,5]]

기본 배열에 액세스하고 해당 tolist메서드를 호출 할 수 있습니다 .

>>> df = pd.DataFrame([[1,2,3],[3,4,5]])
>>> lol = df.values.tolist()
>>> lol
[[1L, 2L, 3L], [3L, 4L, 5L]]

데이터에 보존하려는 열 및 색인 레이블이있는 경우 몇 가지 옵션이 있습니다.

예제 데이터 :

>>> df = pd.DataFrame([[1,2,3],[3,4,5]], \
       columns=('first', 'second', 'third'), \
       index=('alpha', 'beta')) 
>>> df
       first  second  third
alpha      1       2      3
beta       3       4      5

tolist()다른 답변에서 설명하는 방법은 유용하지만 수익률 만 핵심 데이터 - 필요에 따라 충분하지 않을 수있다.

>>> df.values.tolist()
[[1, 2, 3], [3, 4, 5]]

한 가지 방법 DataFrame은를 사용하여 json 으로 변환 df.to_json()한 다음 다시 구문 분석하는 것입니다. 이것은 번거롭지 만 to_json()몇 가지 유용한 옵션이 있기 때문에 몇 가지 장점 이 있습니다.

>>> df.to_json()
{
  "first":{"alpha":1,"beta":3},
  "second":{"alpha":2,"beta":4},"third":{"alpha":3,"beta":5}
}

>>> df.to_json(orient='split')
{
 "columns":["first","second","third"],
 "index":["alpha","beta"],
 "data":[[1,2,3],[3,4,5]]
}

번거롭지 만 유용 할 수 있습니다.

좋은 소식은 열과 행에 대한 목록을 작성하는 것이 매우 간단하다는 것입니다.

>>> columns = [df.index.name] + [i for i in df.columns]
>>> rows = [[i for i in row] for row in df.itertuples()]

결과 :

>>> print(f"columns: {columns}\nrows: {rows}") 
columns: [None, 'first', 'second', 'third']
rows: [['alpha', 1, 2, 3], ['beta', 3, 4, 5]]

(가)의 경우 None인덱스의 이름을 귀찮은이기 때문에, 이름을 변경합니다 :

df = df.rename_axis('stage')

그때:

>>> columns = [df.index.name] + [i for i in df.columns]
>>> print(f"columns: {columns}\nrows: {rows}") 

columns: ['stage', 'first', 'second', 'third']
rows: [['alpha', 1, 2, 3], ['beta', 3, 4, 5]]

귀하의 요구 사항에 맞는지 모르겠지만 다음과 같이 할 수도 있습니다.

>>> lol = df.values
>>> lol
array([[1, 2, 3],
       [3, 4, 5]])

이것은 ndarray 모듈의 numpy 배열 일 뿐이며 일반적인 numpy 배열 작업을 모두 수행 할 수 있습니다.


아마도 뭔가 변경되었지만 이것은 내가 필요한 것을 한 ndarrays 목록을 돌려주었습니다.

list(df.values)

색인을 보존하고 싶었으므로이 솔루션에 대한 원래 답변을 수정했습니다.

df.reset_index().values.tolist()

이제 다른 곳에서 다시 만들려면 (예 : Stack Overflow 질문에서 과거) :

pd.Dataframe(<data-printed-above>, columns=['name1', ...])
pd.set_index(['name1'], inplace=True)

참고 URL : https://stackoverflow.com/questions/28006793/pandas-dataframe-to-list-of-lists

반응형