问题:将列表或系列作为一行附加到熊猫DataFrame吗?

因此,我已经初始化了一个空的Pandas DataFrame,并希望迭代地将列表(或Series)追加为该DataFrame中的行。最好的方法是什么?

So I have initialized an empty pandas DataFrame and I would like to iteratively append lists (or Series) as rows in this DataFrame. What is the best way of doing this?


回答 0

有时,在熊猫之​​外进行所有附加操作会更容易,然后只需创建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

Sometimes it’s easier to do all the appending outside of pandas, then, just create the DataFrame in one shot.

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

回答 1

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

回答 2

这是一个简单而愚蠢的解决方案:

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

Here’s a simple and dumb solution:

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

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

有谁有更优雅的解决方案?

Could you do something like this?

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

Does anyone have a more elegant solution?


回答 4

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

Following onto Mike Chirico’s answer… if you want to append a list after the dataframe is already populated…

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

回答 5

如果要添加一个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你没有得到正确的索引。

If you want to add a Series and use the Series’ index as columns of the DataFrame, you only need to append the Series between brackets:

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.


回答 6

这是一个给定已经创建的数据框的函数,该函数会将列表作为新行追加。这可能应该抛出错误捕获器,但是如果您确切知道要添加的内容,那应该不是问题。

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

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

回答 7

将列表转换为append函数中的数据框也有效,即使在循环中应用也是如此

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

Converting the list to a data frame within the append function works, also when applied in a loop

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

回答 8

只需使用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

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

回答 9

如此处所述-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)

As mentioned here – https://kite.com/python/answers/how-to-append-a-list-as-a-row-to-a-pandas-dataframe-in-python, you’ll need to first convert the list to a series then append the series to dataframe.

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)

回答 10

最简单的方法:

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

编辑:

不要忘记,新列表的长度应与相应数据框的长度相同。

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.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。