首页 > 解决方案 > 从两个不完整的、不同大小的数据框创建日期上的数据框

问题描述

我正在尝试将一个包含日期、平均情绪得分(来自 Twitter)和收盘价的大数据框放在一起。

这是我到目前为止所拥有的。

#imports
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import re
import urllib3
import requests
import datetime 

#mydates dataframe that just has the dates from my desired range. Shape is 2008 rows x 1 column
date1='2014-01-01'
date2='2019-07-01'
mydates =pd.date_range(date1,date2).tolist()
newdf =pd.DataFrame({'Date':mydates})

#df with the average daily sentiment scores. Large dataset with 500 rows.
#This currently skips dates that didn't have tweets.I want to include those dates but have sentiment equal 0.
Date        Score
2014-01-13  0.01
2014-01-14  0.035
2014-01-15  0.453
2014-01-20  0.06474

#ts dataframe of dates and stock prices. Shape is 1381 rows x 1 column
Date         Adj Close
2014-01-13  44.8
2014-01-14  45.3
2014-01-15  45.8
2014-01-16  46.5
2014-01-17  46.5
2014-01-21  46.7

期望的输出

Date        Score   Close Price
2014-01-13  0.01     44.8
2014-01-14  0.035    45.3
2014-01-15  0.453    45.8
2014-01-16  0.0      46.5
2014-01-17  0.0      46.5
2014-01-18  0.0      46.5
2014-01-19  0.0      46.5
2014-01-20  0.06474  46.5

我的计划是将此数据集保存为 csv。

我遇到的问题: Df 和 ts 的大小不同。我需要通过 ts 使所有周末收盘价与周五相同。我怎么做?不知道如何编写一个循环,可以将一个数据帧中日期的分数分配给另一个数据帧中的列。

我使用熊猫-3。

标签: python-3.xpandasdataframesentiment-analysisstock

解决方案


设置dfas的索引Date并用于DataFrame.asfreq在每日频率上重新索引数据框,然后将其与on column合并,最后在 column上使用:DataFrame.merge lefttsDateSeries.ffillAdj Close

df1 = (
    df.set_index('Date').
    asfreq('D', fill_value=0).reset_index().merge(ts, on='Date', how='left')
)
df1['Adj Close'] = df1['Adj Close'].ffill()

结果:

print(df1)
        Date    Score  Adj Close
0 2014-01-13  0.01000       44.8
1 2014-01-14  0.03500       45.3
2 2014-01-15  0.45300       45.8
3 2014-01-16  0.00000       46.5
4 2014-01-17  0.00000       46.5
5 2014-01-18  0.00000       46.5
6 2014-01-19  0.00000       46.5
7 2014-01-20  0.06474       46.5

推荐阅读