python-3.x - 从两个不完整的、不同大小的数据框创建日期上的数据框
问题描述
我正在尝试将一个包含日期、平均情绪得分(来自 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。
解决方案
设置df
as的索引Date
并用于DataFrame.asfreq
在每日频率上重新索引数据框,然后将其与on column合并,最后在 column上使用:DataFrame.merge
left
ts
Date
Series.ffill
Adj 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
推荐阅读
- jquery - scrollTop 在 iframe 中时不起作用
- c# - 如何以编程方式将任务添加到特定的 Outlook 存储
- julia - Julia:抽象类型的覆盖函数没有被调用
- django - 如何仅使用社交媒体身份验证但也仅通过管理员用户邀请对新用户进行身份验证?
- java - 单击项目后如何关闭回收站视图持有者?
- arduino - 无法获得柔性传感器的恒定值
- netlogo - 在 Netogo 上创建游戏 Snake
- python - 为什么我的 Miller-Rabin 算法实现无法检测到某些素数?
- android - 获取文件的访问时间
- apache-camel - NoClassDefFoundError: OsgiDefaultCamelContext 使用 Apache ServiceMix