>>> df1
AAPL GOOG
Date
2016-03-01 0.013422 -0.321900
2016-03-02 -0.012341 -0.000800
2016-03-03 -0.000772 0.055500
2016-03-07 -0.413103 -0.009555
>>> df2
NFLX FB
Date
2016-03-01 0.013422 -0.321900
2016-03-02 -0.012341 -0.000800
2016-03-03 -0.000772 0.055500
2016-03-07 -0.413103 -0.009555
我希望能够使用时间戳编制索引。但这给了我一个错误。例如,如果我想这样做:
df1['2016-03-01']
这有效并返回df1的第一行。 但是如果我这样做:
df1[df2.index[0]]
这不起作用,返回并出错。我正在编码一些迭代日期的内容,而我正努力寻找解决方案。请帮助
答案 0 :(得分:1)
制作您的dfs
df1 = pd.DataFrame({"Date": ["2016-03-01","2016-03-02","2016-03-03","2016-03-07"],
"AAPL": [0.013422,-0.012341,-0.000772,-0.413103],
"GOOG": [-0.321900,-0.000800,0.055500,-0.009555]})
df2 = pd.DataFrame({"Date": ["2016-03-18"],
"NFLX": [0.23525],
"FB": [-0.28942]})
# set date to datetime
df1["Date"],df2["Date"] = pd.to_datetime(df1["Date"]),pd.to_datetime(df2["Date"])
# set Date as index
df1,df2 = df1.set_index("Date"),df2.set_index("Date")
# output1
>>> df1
AAPL GOOG
Date
2016-03-01 0.013422 -0.321900
2016-03-02 -0.012341 -0.000800
2016-03-03 -0.000772 0.055500
2016-03-07 -0.413103 -0.009555
# output2
>>> df2
NFLX FB
Date
2016-03-01 0.235250 -0.289420
按索引从df2向df1添加行
for i,j in enumerate(df1.index):
df2 = df2.append(df1.iloc[[i]],sort=True)
>>> df2
AAPL FB GOOG NFLX
Date
2016-03-18 NaN -0.28942 NaN 0.23525
2016-03-01 0.013422 NaN -0.321900 NaN
2016-03-02 -0.012341 NaN -0.000800 NaN
2016-03-03 -0.000772 NaN 0.055500 NaN
2016-03-07 -0.413103 NaN -0.009555 NaN