Dołączanie listy lub serii do ramki danych pandy jako wiersz?

Więc zainicjowałem pustą ramkę danych pandy i chciałbym iteracyjnie dopisać listy (lub serie) jako wiersze w tej ramce danych. Jak najlepiej to zrobić?

Author: Wes Field, 2014-10-11

13 answers

Czasami łatwiej jest zrobić wszystkie dodawanie poza pand, a następnie po prostu utworzyć ramkę danych w jednym ujęciu.

>>> 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
 144
Author: Mike Chirico,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-04-18 09:51:13
df = pd.DataFrame(columns=list("ABC"))
df.loc[len(df)] = [1,2,3]
 123
Author: Ashot Matevosyan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-25 09:59:54

Oto proste i głupie rozwiązanie:

>>> import pandas as pd
>>> df = pd.DataFrame()
>>> df = df.append({'foo':1, 'bar':2}, ignore_index=True)
 62
Author: Jaidev Deshpande,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-11 04:37:54

Mógłbyś zrobić coś takiego?

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

Czy ktoś ma bardziej eleganckie rozwiązanie?

 39
Author: Alex Woolford,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-11 02:01:52

Podążając za odpowiedzią Mike ' a Chirico... jeśli chcesz dodać listę po ramka danych jest już wypełniona...

>>> 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
 28
Author: Jay Marm,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-19 16:55:48

Oto funkcja, która, biorąc pod uwagę już utworzoną ramkę danych, doda listę jako nowy wiersz. Prawdopodobnie powinno to zawierać wykrywacze błędów, ale jeśli wiesz dokładnie, co dodajesz, nie powinno to być problemem.

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
 5
Author: jadki,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-04 22:05:22

Jeśli chcesz dodać serię i użyć indeksu serii jako kolumn ramki danych, wystarczy dodać serię między nawiasami:

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]

Whitout the ignore_index=True you don ' t get proper index.

 4
Author: bmello,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-03 02:51:57

Konwersja listy do ramki danych w funkcji append działa, również wtedy, gdy jest zastosowana w pętli

import pandas as pd
mylist = [1,2,3]
df = pd.DataFrame()
df = df.append(pd.DataFrame(data[mylist]))
 4
Author: janfelix,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-11-14 21:37:26

Po prostu użyj 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
 3
Author: Qinsi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-30 03:23:18

Istnieje kilka sposobów na dołączenie listy do ramki danych Panda w Pythonie. Rozważmy następujący dataframe i listę:

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

Opcja 1: Dodaj listę na końcu ramki danych za pomocą pandas.DataFrame.loc.

df.loc[len(df)] = list

Opcja 2: Konwertuj listę na ramkę danych i Dołącz za pomocą pandas.DataFrame.append().

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

Opcja 3: Konwertuj listę na serię i Dołącz za pomocą pandas.DataFrame.append().

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

Każda z powyższych opcji powinna wypisać coś like:

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

Referencja: Jak dodać listę jako wiersz do ramki danych Panda w Pythonie?

 3
Author: Fifi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-12-31 12:40:46

Jak wspomniano tutaj - https://kite.com/python/answers/how-to-append-a-list-as-a-row-to-a-pandas-dataframe-in-python, Musisz najpierw przekonwertować listę na serię, a następnie dołączyć serię do ramki danych.

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)
 2
Author: Abhishek Poojary,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-06-20 18:54:45

Najprostszy sposób:

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

Edit:

Nie zapominaj, że długość nowej listy powinna być taka sama jak odpowiedniej ramki danych.

 0
Author: user_007,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-12-14 18:48:20

Rozważmy tablicę A o wymiarach N x 2. Aby dodać jeszcze jeden wiersz, użyj poniższej opcji.

A.loc[A.shape[0]] = [3,4]
 0
Author: Samiran Bera,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2021-01-09 13:21:24