简体   繁体   English

按日期时间和日期列合并 Pandas Dataframe

[英]Merging Pandas Dataframe by Datetime and Date column

I have two Dataframes looking the following.我有两个如下所示的数据框。

timestamp                 data
2015-01-01 00:00:00       296.0
2015-01-01 00:30:00       342.0
2015-01-01 01:00:00       431.0
2015-01-01 01:30:00       234.0
2015-01-01 02:00:00       234.0
...
2015-02-01 00:00:00       123.0
...

and

date             different date
2015-01-01       111
2015-01-02       233
2015-01-03       1324
2015-01-04       1231
2015-01-05       112
...

What I want is我想要的是

timestamp                 data     different date
2015-01-01 00:00:00       296.0    111
2015-01-01 00:30:00       342.0    111
2015-01-01 01:00:00       431.0    111
2015-01-01 01:30:00       234.0    111
2015-01-01 02:00:00       234.0    111
...
2015-02-01 00:00:00       123.0    233
...

So what I want is a merge from one dataframe to the other.所以我想要的是从一个 dataframe 合并到另一个。 Where If the date is the same, every datetime row that fits the day gets the other value.如果日期相同,则适合该日期的每个日期时间行都会获得另一个值。 Unfortunately my secound dataframe (the one with one value per day) has missing rows, so I cant just expand every value 48 times.不幸的是,我的第二个 dataframe(每天只有一个值)缺少行,所以我不能将每个值都扩展 48 次。 Any help is appreciated.任何帮助表示赞赏。 Looping over both dataframes and comparing the date seems very inefficient.循环遍历两个数据框并比较日期似乎非常低效。

You can create helper column filled by dates from datetimes in df1 and then merge by it with left join by DataFrame.merge , last if necessary remove this column:您可以在df1中创建由 datetimes 中的日期填充的帮助列,然后通过DataFrame.merge将其与左连接合并,最后在必要时删除此列:

df1['timestamp'] = pd.to_datetime(df1['timestamp'])
df2['date'] = pd.to_datetime(df2['date']).dt.date

df1['date'] = df1['timestamp'].dt.date

df = df1.merge(df2, on='date', how='left').drop('date', axis=1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM