programing

머리글 및 행 목록을 팬더 데이터 프레임으로 변환

oldcodes 2023. 8. 12. 10:40
반응형

머리글 및 행 목록을 팬더 데이터 프레임으로 변환

저는 스프레드시트의 내용을 팬더에게 읽어주는 중입니다.DataNitro는 직사각형 셀 선택을 목록으로 반환하는 방법을 가지고 있습니다. 그래서

table = Cell("A1").table

기브즈

table = [['Heading1', 'Heading2'], [1 , 2], [3, 4]]

headers = table.pop(0) # gives the headers as list and leaves data

이것을 번역하기 위해 코드를 작성하느라 바쁘지만, 제 생각에는 이것은 매우 간단한 사용이기 때문에 이것을 할 수 있는 방법이 있을 것입니다.문서에서 찾을 수 없는 것 같습니다.이것을 단순화하는 방법에 대한 조언이 있습니까?

콜 더pd.DataFrame생성자 직접:

df = pd.DataFrame(table, columns=headers)
df

   Heading1  Heading2
0         1         2
1         3         4

위의 EdChum에서 설명한 접근 방식에서는 목록의 값이 행으로 표시됩니다.대신 목록 값을 DataFrame에서 열로 표시하려면 다음과 같이 transcose()를 사용합니다.

table = [[1 , 2], [3, 4]]
df = pd.DataFrame(table)
df = df.transpose()
df.columns = ['Heading1', 'Heading2']

그러면 출력은 다음과 같습니다.

      Heading1  Heading2
0         1        3
1         2        4

없이도pop우리가 할 수 있는 목록set_index

pd.DataFrame(table).T.set_index(0).T
Out[11]: 
0 Heading1 Heading2
1        1        2
2        3        4

갱신하다from_records

table = [['Heading1', 'Heading2'], [1 , 2], [3, 4]]

pd.DataFrame.from_records(table[1:],columns=table[0])
Out[58]: 
   Heading1  Heading2
0         1         2
1         3         4

에서table예제, 호출DataFrame생성자는 다음과 같습니다.

table = [['Heading1', 'Heading2'], [1 , 2], [3, 4]]

df = pd.DataFrame(table[1:], columns=table[0])

언급URL : https://stackoverflow.com/questions/19112398/converting-list-of-header-and-row-lists-into-pandas-dataframe

반응형