亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 timedelta 將 df1 中的每一行的 pandas DataFrame

使用 timedelta 將 df1 中的每一行的 pandas DataFrame

喵喔喔 2022-07-05 17:13:45
我有兩個熊貓數據框。我想將所有行保留在df2等于Typein TypeANDdf1之間Date(Date- df11 天或 + 1 天)。我怎樣才能做到這一點?df1   IBSN  Type          Date0     1     X    2014-08-171     1     Y    2019-09-22df2   IBSN  Type          Date0     2     X    2014-08-161     2     D    2019-09-222     9     X    2014-08-183     3     H    2019-09-224     3     Y    2019-09-235     5     G    2019-09-22資源   IBSN  Type          Date0     2     X    2014-08-16 <-- keep because Type = df1[0]['Type'] AND Date = df1[0]['Date'] - 11     9     X    2014-08-18 <-- keep because Type = df1[0]['Type'] AND Date = df1[0]['Date'] + 12     3     Y    2019-09-23 <-- keep because Type = df1[1]['Type'] AND Date = df1[1]['Date'] + 1
查看完整描述

2 回答

?
月關寶盒

TA貢獻1772條經驗 獲得超5個贊

這應該這樣做:


import pandas as pd

from datetime import timedelta


# create dummy data

df1 = pd.DataFrame([[1, 'X', '2014-08-17'], [1, 'Y', '2019-09-22']], columns=['IBSN', 'Type', 'Date'])

df1['Date'] = pd.to_datetime(df1['Date'])  # might not be necessary if your Date column already contain datetime objects


df2 = pd.DataFrame([[2, 'X', '2014-08-16'], [2, 'D', '2019-09-22'], [9, 'X', '2014-08-18'], [3, 'H', '2019-09-22'], [3, 'Y', '2014-09-23'], [5, 'G', '2019-09-22']], columns=['IBSN', 'Type', 'Date'])

df2['Date'] = pd.to_datetime(df2['Date'])  # might not be necessary if your Date column already contain datetime objects



# add date boundaries to the first dataframe

df1['Date_from'] = df1['Date'].apply(lambda x: x - timedelta(days=1))

df1['Date_to'] = df1['Date'].apply(lambda x: x + timedelta(days=1))


# merge the date boundaries to df2 on 'Type'. Filter rows where date is between

# data_from and date_to (inclusive). Drop 'date_from' and 'date_to' columns

df2 = df2.merge(df1.loc[:, ['Type', 'Date_from', 'Date_to']], on='Type', how='left')

df2[(df2['Date'] >= df2['Date_from']) & (df2['Date'] <= df2['Date_to'])].\

    drop(['Date_from', 'Date_to'], axis=1)

請注意,根據您的邏輯,df2(3 Y 2014-09-23)中的第 4 行不應保留,因為其日期(2014)不在 df1(2019 年)的給定日期之間。


查看完整回答
反對 回復 2022-07-05
?
白豬掌柜的

TA貢獻1893條經驗 獲得超10個贊

假設Date兩個數據框中的列已經在 dtype 中datetime。我會構造IntervalIndex分配給df1. to的Map列Type。最后檢查相等性以創建要切片的掩碼df1df2


iix = pd.IntervalIndex.from_arrays(df1.Date + pd.Timedelta(days=-1), 

                                   df1.Date + pd.Timedelta(days=1), closed='both')

df1 = df1.set_index(iix)

s = df2['Date'].map(df1.Type)

df_final = df2[df2.Type == s]


Out[1131]:

   IBSN Type       Date

0     2    X 2014-08-16

2     9    X 2014-08-18

4     3    Y 2019-09-23


查看完整回答
反對 回復 2022-07-05
  • 2 回答
  • 0 關注
  • 143 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號