【问题标题】:Appending a list or series to a pandas DataFrame as a row?将列表或系列作为一行附加到 pandas DataFrame?
【发布时间】:2014-12-06 05:53:34
【问题描述】:

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

【问题讨论】:

标签: python pandas append dataframe


【解决方案1】:

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

【讨论】:

  • 这个问题似乎暗示并非所有行都是预先知道的。
  • 这不能回答 OP 的问题。
【解决方案2】:
df = pd.DataFrame(columns=list("ABC"))
df.loc[len(df)] = [1,2,3]

【讨论】:

  • 如果您希望添加到 df 的末尾,这是最简单的。
  • 这正是我想要的,简单而有效!
  • 为什么这不是选择的答案?
  • 这通常没问题,但仅当您有一个从 0 开始的单调递增索引时才有效。
【解决方案3】:

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

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

【讨论】:

  • 请注意,这是附加一个字典,而不是一个列表
【解决方案4】:

你能做这样的事情吗?

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

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

【讨论】:

  • 这是一个更简单和愚蠢的解决方案:``` import pandas as pd df = pd.DataFrame() df = df.append({'foo':1, 'bar':2}, ignore_index =True) # 请注意,此附加不会发生在适当的位置。 ```
  • index 参数应该命名为columns; ignore_index 这里忽略了索引 - 系列的名称。
【解决方案5】:

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

【讨论】:

  • 它会创建副本吗?是否可以就地追加?
  • @lucid_dreamer 这会创建一个副本。
  • ignore_index 参数是可选的(默认为False)。
【解决方案6】:

在 Python 中有多种方法可以将列表附加到 Pandas 数据框。让我们考虑以下数据框和列表:

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

选项 1: 将列表附加到数据框的末尾,并加上 pandas.DataFrame.loc。

df.loc[len(df)] = list

选项 2: 将列表转换为数据框并附加 pandas.DataFrame.append()。

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

选项 3: 将列表转换为系列并附加 pandas.DataFrame.append()。

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

上述每个选项都应输出如下内容:

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

参考:How to append a list as a row to a Pandas DataFrame in Python?

【讨论】:

【解决方案7】:

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

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

【讨论】:

  • data[mylist] 是什么?显然,它会抛出错误NameError: name 'data' is not defined。五票表明他们知道?
  • 正确的应该是 df = df.append(pd.DataFrame(data=[mylist])) 。数据后缺少“=”。
【解决方案8】:

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

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

【讨论】:

    【解决方案9】:

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

    【讨论】:

      【解决方案10】:

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

      【讨论】:

        【解决方案11】:

        正如这里提到的 - 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)
        

        【讨论】:

          【解决方案12】:

          考虑一个 N x 2 维的数组 A。要再添加一行,请使用以下命令。

          A.loc[A.shape[0]] = [3,4]
          

          【讨论】:

          • 您可以为带有 3 个反引号的代码创建代码块
          【解决方案13】:

          最简单的方法:

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

          编辑:

          别忘了新列表的长度应该和对应的Dataframe一样。

          【讨论】:

          • 这适用于列表的单个实例,但如果你有多次出现而不是我的版本工作
          猜你喜欢
          • 2017-05-21
          • 2020-03-04
          • 2019-05-24
          • 2014-05-19
          • 2015-03-06
          • 1970-01-01
          • 2019-08-17
          • 2021-07-27
          • 2018-05-06
          相关资源
          最近更新 更多