[python] 목록이나 시리즈를 Pandas DataFrame에 행으로 추가 하시겠습니까?

그래서 빈 pandas DataFrame을 초기화했으며이 DataFrame의 행으로 목록 (또는 시리즈)을 반복적으로 추가하고 싶습니다. 이를 수행하는 가장 좋은 방법은 무엇입니까?



답변

때때로 Pandas 외부에서 모든 추가 작업을 수행하는 것이 더 쉬울 때도 있습니다. 그런 다음 한 번에 DataFrame을 생성하기 만하면됩니다.

>>> 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


답변

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


답변

다음은 간단하고 멍청한 솔루션입니다.

>>> 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

누구보다 우아한 솔루션이 있습니까?


답변

Mike Chirico의 대답에 따라 … 데이터 프레임이 이미 채워진 후에 목록을 추가 하려면 …

>>> 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


답변

Series를 추가하고 Series의 인덱스를 DataFrame의 열로 사용하려면 대괄호 사이에 Series를 추가하기 만하면됩니다.

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당신은 적절한 색인을 얻지 못합니다.


답변

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

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