programing

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

nasanasas 2020. 10. 6. 08:18
반응형

목록이나 시리즈를 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

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

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

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

이런 식으로 할 수 있습니까?

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


Here's a function that, given an already created dataframe, will append a list as a new row. This should probably have error catchers thrown in, but if you know exactly what you're adding then it shouldn't be an issue.

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

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

The simplest way:

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

Edit:

Don't forget that the length of the new list should be the same of the corresponding Dataframe.

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

반응형