我该如何将一个Pandas数据框的一行复制到另一个Pandas数据框中?

25

我有一个数据框,想将其附加到另一个数据框中。我尝试了各种方法,包括使用.append(),但都没有成功。当我从iterrows打印数据时,我提供了下面两种解决问题的方法:一种会创建错误,另一种则不会在数据框中填充任何内容。

我正在尝试创建的工作流是基于包含客户订单交易历史记录的文件创建数据框。我只想为每个订单创建一条记录,并将其他逻辑添加到根据历史记录更新订单详细信息的操作中。在脚本结束时,它将具有所有订单的单个记录以及通过历史记录迭代后的订单的最终状态。

class order_manager():
    """Manages over the current state of orders"""
    
    def __init__(self,dataF, desc='NONE'):
        self.df = pd.DataFrame
        self.data = dataF
        print type(dataF)
        self.oD= self.df(data=None,columns=desc)
    
    def add_data(self,df):
        for i, row in self.data.iterrows():
            print 'row '+str(row)
            print type(row)
            df.append(self.data[i], ignore_index =True) """ This line creates and error"""
            df.append(row, ignore_index =True) """This line doesn't append anything to the dataframe."""

test = order_manager(body,header)
test.add_data(test.orderData)

我认为你只需要使用 pd.concat([df1, df2])。不需要逐行迭代地添加。 - chrisaycock
你看过append示例了吗? - Ami Tavory
2022年的注意事项:append已被弃用,应使用concat - RocketMan
2个回答

17

使用.loc来扩大当前的df。请参见下面的例子。

import pandas as pd
import numpy as np

date_rng = pd.date_range('2015-01-01', periods=200, freq='D')

df1 = pd.DataFrame(np.random.randn(100, 3), columns='A B C'.split(), index=date_rng[:100])
Out[410]: 
                 A       B       C
2015-01-01  0.2799  0.4416 -0.7474
2015-01-02 -0.4983  0.1490 -0.2599
2015-01-03  0.4101  1.2622 -1.8081
2015-01-04  1.1976 -0.7410  0.4221
2015-01-05  1.3311  1.0399  2.2701
...            ...     ...     ...
2015-04-06 -0.0432  0.6131 -0.0216
2015-04-07  0.4224 -1.1565  2.2285
2015-04-08  0.0663  1.2994  2.0322
2015-04-09  0.1958 -0.4412  0.3924
2015-04-10  0.1622  1.7603  1.4525

[100 rows x 3 columns]


df2 = pd.DataFrame(np.random.randn(100, 3), columns='A B C'.split(), index=date_rng[100:])
Out[411]: 
                 A       B       C
2015-04-11  1.1196 -1.9627  0.6615
2015-04-12 -0.0098  1.7655  0.0447
2015-04-13 -1.7318 -2.0296  0.8384
2015-04-14 -1.5472 -1.7220 -0.3166
2015-04-15  2.5058  0.6487  1.0994
...            ...     ...     ...
2015-07-15 -1.4803  2.1703 -1.9391
2015-07-16 -1.7595 -1.7647 -1.0622
2015-07-17  1.7900  0.2280 -1.8797
2015-07-18  0.7909 -0.4999  0.3848
2015-07-19  1.2243  0.4681 -1.2323

[100 rows x 3 columns]

# to move one row from df2 to df1, use .loc to enlarge df1
# this is far more efficient than pd.concat and pd.append
df1.loc[df2.index[0]] = df2.iloc[0]

Out[413]: 
                 A       B       C
2015-01-01  0.2799  0.4416 -0.7474
2015-01-02 -0.4983  0.1490 -0.2599
2015-01-03  0.4101  1.2622 -1.8081
2015-01-04  1.1976 -0.7410  0.4221
2015-01-05  1.3311  1.0399  2.2701
...            ...     ...     ...
2015-04-07  0.4224 -1.1565  2.2285
2015-04-08  0.0663  1.2994  2.0322
2015-04-09  0.1958 -0.4412  0.3924
2015-04-10  0.1622  1.7603  1.4525
2015-04-11  1.1196 -1.9627  0.6615

[101 rows x 3 columns]

我不确定它比pandas的append更有效率多少,两者对我来说都非常慢。 - matanster

0
Pandas 数据帧不适合原地垂直增长。使用循环添加行非常缓慢的原因是有道理的。使用 pd.concat 创建新框架要快得多。因此,与其使用 iterrows() 进行循环实现,最好使用连接操作。
def add_data(self, df):
    self.data = pd.concat([self.data, df], ignore_index=True)

如果需要一些逻辑(例如值必须唯一等),那么最好在连接之前使用布尔索引来过滤df,或者在连接后调用drop_duplicates()。换句话说,有其他可用的方法来处理数据。

话虽如此,对于单行数据,loc很好用。要将df的第一行附加到self.data,可以使用以下方法。请注意,它仅在列名重叠时有效;否则会出现一堆NaN。

self.data.iloc[len(self.data)] = df.iloc[0]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接