Python 将列表或系列作为一行附加到 Pandas DataFrame?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26309962/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:20:50  来源:igfitidea点击:

Appending a list or series to a pandas DataFrame as a row?

pythonpandasappenddataframe

提问by Wes Field

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?

所以我已经初始化了一个空的 Pandas DataFrame,我想迭代地附加列表(或系列)作为这个 DataFrame 中的行。这样做的最佳方法是什么?

采纳答案by Mike Chirico

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

有时在 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

回答by Alex Woolford

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?

有没有人有更优雅的解决方案?

回答by Jaidev Deshpande

Here's a simple and dumb solution:

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

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

回答by Jay Marm

Following onto Mike Chirico's answer... if you want to append a list afterthe dataframe is already populated...

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

回答by bmello

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:

如果要添加 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]

Whitout the ignore_index=Trueyou don't get proper index.

Whitout在ignore_index=True你没有得到正确的索引。

回答by Ashot Matevosyan

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

回答by jadki

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

回答by Qinsi

simply use loc:

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

回答by Ghanem

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.

不要忘记新列表的长度应该与对应的 Dataframe 相同。

回答by janfelix

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

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

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