programing

판다 데이터 프레임에 목록이나 시리즈를 행으로 추가하시겠습니까?

css3 2023. 6. 29. 20:20

판다 데이터 프레임에 목록이나 시리즈를 행으로 추가하시겠습니까?

빈 판다 DataFrame을 초기화했으며 목록(또는 시리즈)을 이 DataFrame의 행으로 반복적으로 추가하려고 합니다.이것을 하는 가장 좋은 방법은 무엇입니까?

df = pd.DataFrame(columns=list("ABC"))
df.loc[len(df)] = [1,2,3]

때때로 팬더 밖에서 모든 추가 작업을 수행하는 것이 더 쉬우며, 한 번의 촬영으로 데이터 프레임을 생성할 수 있습니다.

>>> import pandas as pd
>>> simple_list=[['a','b']]
>>> simple_list.append(['e','f'])
>>> df=pd.DataFrame(simple_list,columns=['col1','col2'])
   col1 col2
0    a    b
1    e    f

여기 간단하고 멍청한 해결책이 있습니다.

>>> import pandas as pd
>>> df = pd.DataFrame()
>>> df = df.append({'foo':1, 'bar':2}, ignore_index=True)

당신은 이런 것을 할 수 있습니까?

>>> import pandas as pd
>>> df = pd.DataFrame(columns=['col1', 'col2'])
>>> df = df.append(pd.Series(['a', 'b'], index=['col1','col2']), ignore_index=True)
>>> df = df.append(pd.Series(['d', 'e'], index=['col1','col2']), ignore_index=True) 
>>> df
  col1 col2
0    a    b
1    d    e

좀 더 우아한 해결책을 가진 사람이 있습니까?

마이크 치리코의 대답에 이어...데이터 프레임이 이미 채워진 후 목록을 추가하려면...

>>> list = [['f','g']]
>>> df = df.append(pd.DataFrame(list, columns=['col1','col2']),ignore_index=True)
>>> df
  col1 col2
0    a    b
1    d    e
2    f    g

Python에서 Pandas 데이터 프레임에 목록을 추가하는 몇 가지 방법이 있습니다.다음 데이터 프레임과 목록을 고려해 보겠습니다.

import pandas as pd
# Dataframe
df = pd.DataFrame([[1, 2], [3, 4]], columns = ["col1", "col2"])
# List to append
list = [5, 6]

옵션 1: 데이터 프레임의 끝에 목록을 추가합니다.pandas.DataFrame.loc.

df.loc[len(df)] = list

옵션 2: 목록을 데이터 프레임으로 변환하고 다음을 추가합니다.pandas.DataFrame.append().

df = df.append(pd.DataFrame([list], columns=df.columns), ignore_index=True)

옵션 3: 목록을 시리즈로 변환하고 다음과 함께 추가합니다.pandas.DataFrame.append().

df = df.append(pd.Series(list, index = df.columns), ignore_index=True)

위의 각 옵션은 다음과 같은 것을 출력해야 합니다.

>>> print (df)
   col1  col2
0     1     2
1     3     4
2     5     6

참고 자료: Python에서 Pandas DataFrame에 행으로 목록을 추가하는 방법은 무엇입니까?

추가 기능 내에서 목록을 데이터 프레임으로 변환하면 루프에 적용될 때도 작동합니다.

import pandas as pd
mylist = [1,2,3]
df = pd.DataFrame()
df = df.append(pd.DataFrame(data[mylist]))

여기에 이미 생성된 데이터 프레임이 주어지면 목록을 새 행으로 추가하는 함수가 있습니다.여기에는 오류 탐지기가 포함되어 있어야 하지만, 추가할 내용을 정확히 알고 있다면 문제가 되지 않습니다.

import pandas as pd
import numpy as np

def addRow(df,ls):
    """
    Given a dataframe and a list, append the list as a new row to the dataframe.

    :param df: <DataFrame> The original dataframe
    :param ls: <list> The new row to be added
    :return: <DataFrame> The dataframe with the newly appended row
    """

    numEl = len(ls)

    newRow = pd.DataFrame(np.array(ls).reshape(1,numEl), columns = list(df.columns))

    df = df.append(newRow, ignore_index=True)

    return df

시리즈를 추가하고 시리즈 인덱스를 데이터 프레임의 열로 사용하려면 대괄호 사이에 시리즈를 추가하기만 하면 됩니다.

In [1]: import pandas as pd

In [2]: df = pd.DataFrame()

In [3]: row=pd.Series([1,2,3],["A","B","C"])

In [4]: row
Out[4]: 
A    1
B    2
C    3
dtype: int64

In [5]: df.append([row],ignore_index=True)
Out[5]: 
   A  B  C
0  1  2  3

[1 rows x 3 columns]

화이트아웃 더ignore_index=True당신은 적절한 색인을 얻지 못합니다.

loc을 사용하면 됩니다.

>>> df
     A  B  C
one  1  2  3
>>> df.loc["two"] = [4,5,6]
>>> df
     A  B  C
one  1  2  3
two  4  5  6

N x 2 차원의 배열 A를 고려합니다.행을 하나 더 추가하려면 다음을 사용합니다.

A.loc[A.shape[0]] = [3,4]

여기서 언급한 것처럼 https://kite.com/python/answers/how-to-append-a-list-as-a-row-to-a-pandas-dataframe-in-python, 에서 먼저 목록을 시리즈로 변환한 다음 시리즈를 데이터 프레임에 추가해야 합니다.

df = pd.DataFrame([[1, 2], [3, 4]], columns = ["a", "b"])
to_append = [5, 6]
a_series = pd.Series(to_append, index = df.columns)
df = df.append(a_series, ignore_index=True)

가장 간단한 방법:

my_list = [1,2,3,4,5]
df['new_column'] = pd.Series(my_list).values

편집:

새 목록의 길이는 해당 데이터 프레임과 같아야 합니다.

언급URL : https://stackoverflow.com/questions/26309962/appending-a-list-or-series-to-a-pandas-dataframe-as-a-row