熊猫追加行为

时间:2013-11-05 20:14:51

标签: python pandas

这是我在文档中不太确定的内容。

假设我有两个数据帧,数据重叠。

DF1的DateTimeIndex从07:00:00开始,到09:30:00结束。

DF2的DateTimeIndex从07:00:00开始,到11:30:00结束。

DF2是更新的DF1,但在DF1结束时间之前,与DF1相比,可能会添加一些行。所以DF2可能在更新时从9:20:00-9:30:00添加了200行,然后09:30:00之后的所有内容当然也是新的。

如果我使用:

DF1.append(DF2)

我会从DF2获得新的所有行吗?或者pandas只进入并从DF1结束后获取行?除此之外,DF2添加实际上可以与DF1行在同一时间,但它具有不同的内容。大熊猫会处理这个吗?

如果熊猫不能解决这个问题,那么自己最好的方法是什么?

In [489]: df
Out[489]:
                     Row1  Row3
2013-11-05 08:00:00     2   NaN
2013-11-05 09:00:00     4   NaN
2013-11-05 09:06:00     6     5

In [490]: df2
Out[490]:
                     Row1  Row3
2013-11-05 08:00:00     2   NaN
2013-11-05 09:00:00     5   NaN
2013-11-05 09:09:00     6     5

In [491]: df.append(df2)
Out[491]:
                     Row1  Row3
2013-11-05 08:00:00     2   NaN
2013-11-05 09:00:00     4   NaN
2013-11-05 09:06:00     6     5
2013-11-05 08:00:00     2   NaN
2013-11-05 09:00:00     5   NaN
2013-11-05 09:09:00     6     5

我希望df.append(df2)在这种情况下是:

In [491]: df.append(df2)
Out[491]:
                     Row1  Row3
2013-11-05 08:00:00     2   NaN
2013-11-05 09:00:00     4   NaN
2013-11-05 09:06:00     6     5
<strike>2013-11-05 08:00:00     2   NaN</strike>
2013-11-05 09:00:00     5   NaN
2013-11-05 09:09:00     6     5

EDIT2:

我以前这样做过:

last = df.ix[-1].name
to_append = df2[last:]
new_df = df.append(to_append)

这很遗憾地删除了新的行但是在我之前的DataFrame的最后一行的时间戳之前

1 个答案:

答案 0 :(得分:4)

Append与python list类似,您将两个数据帧“堆叠”在一起。在具有重复项的索引的情况下是否引发ValueErrorverify_integrity param控制为append,默认为False

>>> df = pd.DataFrame.from_dict({'col':{'row': 1}})
>>> df
     col
row    1
>>> df.append(df).index
Index([u'row', u'row'], dtype=object)
>>> df.append(df)
     col
row    1
row    1

>>> df.append(df, verify_integrity=True)
Traceback (most recent call last):
   ...
ValueError: Indexes have overlapping values: ['row']

用于合并替换使用combine_first

>>> mdf = pd.DataFrame.from_dict({'col':{'row': 2, 'new':3}})
>>> df.combine_first(mdf) # values from df overwrite those of mdf
     col
new    3
row    1
>>> mdf.combine_first(df) # values from mdf overwrite those of df
     col
new    3
row    2

作为参考,这里是关于数据帧的不同合并和连接方式的extensive guide

<强>更新

跟进:如您所希望的行为类似于SQL union,一种方法是:

>>> df = pd.DataFrame.from_dict({'col':{'row': 1, 'new': 3}})
>>> mdf.append(df).drop_duplicates()
     col
new    3
row    2
row    1

或者,如果您想在帐户中使用索引,

>>> mdf['index'] = mdf.index
>>> df['index'] = df.index
>>> union = mdf.append(df).drop_duplicates()
>>> del union['index']
>>> union
     col
new    3
row    2
row    1