【问题标题】:Pandas append different from documentation [duplicate]熊猫附加与文档不同[重复]
【发布时间】:2021-10-06 07:34:30
【问题描述】:

我在使用 pandas dataframe.append() 时遇到问题,因为它无法按照帮助 (pandas.DataFrame.append) 中描述的方式工作,也无法在各种网站、博客、已回答问题等中在线工作。

这正是我正在做的事情

import pandas as pd
import numpy as np
dataset = pd.DataFrame.from_dict({"0": [0,0,0,0]}, orient="index", columns=["time", "cost", "mult", "class"])
row= [3, 1, 3, 1]
dataset = dataset.append(row, sort=True )

试图得到这个结果

    time   cost  mult  class
0    0.0   0.0   0.0   0.0
1     1     1     1     1

我得到的是

    0    class  cost  mult  time
0  NaN    0.0   0.0   0.0   0.0
0  3.0    NaN   NaN   NaN   NaN
1  1.0    NaN   NaN   NaN   NaN
2  3.0    NaN   NaN   NaN   NaN
3  1.0    NaN   NaN   NaN   NaN

我已经尝试了各种方法,但由于 .append() 不再使用参数“columns”

,因此无法完成一些示例(在线和文档中)

append(self, other, ignore_index: 'bool' = False, verify_integrity: 'bool' = False,排序:'bool' = False) -> 'DataFrame'

other 行追加到调用者的末尾,返回一个新对象。 other : DataFrame 或 Series/dict-like 对象,或这些对象的列表 要附加的数据。

ignore_index : bool,默认 False 如果为 True,则生成的轴将标记为 0、1、...、n - 1。

verify_integrity : bool,默认为 False 如果为 True,则在创建具有重复项的索引时引发 ValueError。

排序:布尔值,默认为 False 如果selfother 的列未对齐,则对列进行排序。

我已经尝试了这些参数的所有组合,但它不断向我显示新行的值在一个新的分隔列上,而且它改变了我在初始数据集中定义的列的顺序。 (我也用 .concat 尝试过各种各样的事情,但它仍然给与 axis=0 类似的问题)

由于即使文档中的示例在具有相同代码结构的情况下也没有显示此结果,如果有人能告诉我发生了什么、为什么以及如何解决这个问题,那就太好了。

针对回答,我已经尝试过了

row= pd.Series([3, 1, 3, 1])
row = row.to_frame()
dataset = dataset.append(row, ignore_index=True )
     0  class  cost  mult  time
0  NaN    0.0   0.0   0.0   0.0
1  3.0    NaN   NaN   NaN   NaN
2  1.0    NaN   NaN   NaN   NaN
3  3.0    NaN   NaN   NaN   NaN
4  1.0    NaN   NaN   NaN   NaN

或者

row= pd.Series([3, 1, 3, 1])
dataset = dataset.append(row, ignore_index=True )

   time  cost  mult  class    0    1    2    3
0   0.0   0.0   0.0    0.0  NaN  NaN  NaN  NaN
1   NaN   NaN   NaN    NaN  3.0  1.0  3.0  1.0

没有ingore_index 在第二种情况下会引发此错误

TypeError:如果 ignore_index=True 或者如果 系列有名字

【问题讨论】:

    标签: python pandas dataframe append concatenation


    【解决方案1】:

    一种选择是将列表显式转换为pd.Series

    In [46]: dataset.append(pd.Series(row, index=dataset.columns), ignore_index=True)
    Out[46]:
       time  cost  mult  class
    0     0     0     0      0
    1     3     1     3      1
    

    您也可以使用 dict 在本机执行此操作:

    In [47]: dataset.append(dict(zip(dataset.columns, row)), ignore_index=True)
    Out[47]:
       time  cost  mult  class
    0     0     0     0      0
    1     3     1     3      1
    

    您遇到的问题是 other 必须是 DataFrameSeries(或另一个类似 dict 的对象)或 DataFrames 或 Serieses 的列表,而不是整数列表。

    【讨论】:

    • 我不明白 index=dataset.columns 代表什么
    • 它将列名映射到Series 索引,以便正确的名称与正确的数字匹配
    猜你喜欢
    • 2013-06-04
    • 2019-01-19
    • 2021-01-25
    • 2021-09-24
    • 2017-03-26
    • 2020-07-29
    • 1970-01-01
    • 2014-12-09
    • 2021-10-01
    相关资源
    最近更新 更多