使用Enlargement进行设置:如何将一行DataFrame添加到另一个DataFrame

时间:2017-07-26 08:33:51

标签: python pandas dataframe

我想创建一个空的DataFrame,其中我会在其他单行DataFrame附加新数据。我正在尝试使用熊猫的“Setting With Enlargement”进行有效的追加。

import numpy as np
import pandas as pd
from datetime import datetime
from pandas import DataFrame

df = DataFrame(columns=["open","high","low","close","volume","open_interest"])

row_one = DataFrame({"open":10,"high":11,"low":9,"close":10,"volume":100,"open_interest":np.NAN}, index = [datetime(2017,1,1)])
row_two = DataFrame({"open":9,"high":12,"low":8,"close":10.50,"volume":500,"open_interest":np.NAN}, index = [datetime(2017,1,2)])

现在,当我尝试使用放大规则追加设置后的新行时:

df[row_one.index] = row_one.columns

我收到此错误:

"DatetimeIndex(['2017-01-01'], dtype='datetime64[ns]', freq=None) not in index"

我认为应该自动添加该行,因为它不在DataFrame中。我做错了什么?

1 个答案:

答案 0 :(得分:0)

您需要loc进行放大设置,然后选择index[0]作为标量,最后转换&#39;通过row_one选择<{1}}到系列:

iloc

但更好的是使用concat,尤其是多个df.loc[row_one.index[0]] = row_one.iloc[0] print (df) open high low close volume open_interest 2017-01-01 10.0 11.0 9.0 10.0 100.0 NaN s:

df