我正在将 API 调用存储到名为 df1 的数据帧(成功)中。 API 调用每天运行两次。我需要将 df1 附加到 df2 中,其中满足以下条件:
1. append rows from df1 into df2 if ID in df1 is not present in df2
2. append rows from df1 into df2 if column 'Updated_Date' in df1 is greater than todays date in df2.
该脚本每天会从 API 中提取数据两次,因此在运行脚本的第一天,df2 中没有数据,但第一天之后的每一天,df1 中都会有来自 API 的记录。所以在第 1 天,df1 和 df2 应该相等。
这是我获取今天日期的方法:
import datetime as dt
benchmark_date = dt.datetime.today().strftime("%m/%d/%y")
这是我如何附加到空数据框中
df2 = df2.append(df1)
我从这里不确定如何构建上述两个步骤中的逻辑。
df1结构:
ID Updated_Date
0 2/14/15
1 2/20/15
提前谢谢您。
最佳答案
假设d1
和d2
中有数据,这应该满足您的条件。
这将创建一个 bool 过滤器以仅选择满足您的条件的行。我可能会将日期时间字符串的格式更改为 YYYY-MM-DD,以便字符串比较正常工作。您也可以将其保留为日期时间格式。如果您需要转换数据框中的字符串列,可以使用 pd.to_datetime
来实现。
benchmark_date = dt.datetime.today().strftime("%Y-%m-%d")
# this filter will satisfy the conditions 1 and 2
df1_filter = ((~df1.ID.isin(df2.ID.unique())) & (df1.Updated_Date > benchmark_date))
# concatenate your original dataframe with new filtered dataframe
df = pd.concat([df2, df1[df1_filter]])
# you can save df which is your combined dataframe
关于python - 如何根据两个条件将一个数据帧追加到另一个空数据帧中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48910912/