【问题标题】:Create a new column in a dataframe based on a date根据日期在数据框中创建一个新列
【发布时间】:2022-01-23 18:54:55
【问题描述】:

我是 python 新手,我想添加一个基于具有多个条件的日期的列。 我的数据来自工作表。

目前我的代码如下所示:

#Save data in a DataFrame

df1 = pd.read_excel(stream_io1, sheet_name = "Sheet1", header=0)

# Use Accounting Date 
df1['Item - Accounting Date'] = pd.to_datetime(df1['Item - Accounting Date'], format='%Y-%m-%d')

def condition(row):
    if (row['Item - Accounting Date'] < '2020-01-01') in row['Item - Accounting Date']:
        return "<2020"
    if "2020" in row['Item - Accounting Date']:
        return "2020"
    if (row[(row['Item - Accounting Date'] >= "01/01/2021") & (row['Item - Accounting Date'] <="30/06/2021")]) in row['Item - Accounting Date']:
        return "S1 2021"    
    if (row[(row['Item - Accounting Date'] > "30/06/2021") & (row['Item - Accounting Date'] <="31/12/2021")]) in row['Item - Accounting Date']:
        return "S2 2021" 

df1['Année'] = df1.apply(condition, axis = 1)

我有这个错误信息:

TypeError:“Timestamp”和“str”实例之间不支持“

我了解错误,但我不知道如何解决它

【问题讨论】:

  • 在比较中使用类似"2021-06-30"的格式始终而不是"30/06/2021"

标签: python pandas dataframe datetime


【解决方案1】:
from datetime import datetime
datetime.strptime("2020-01-01","%Y-%m-%d")

这是将字符串转换为日期时间对象的方法

【讨论】:

  • 嗨@Shen,我是否直接在条件上添加它:row['Item - Accounting Date'] &lt; dt.strptime("2020-01-01","%Y-%m-%d")?因为当我这样做时,我有以下错误 TypeError: argument of type 'Timestamp' is not iterable
  • OP 正在使用熊猫。对于 pandas,您需要使用 pandas 日期时间,而不是标准库的日期时间。
【解决方案2】:

看来您只需要将condition 函数应用于一列,因此您可以使用pd.to_datetime 将其修复如下:

def condition(row):
    if row < pd.Timestamp('2020-01-01'):
        return "<2020"
    if "2020" in row:
        return "2020"
    if (row >= pd.Timestamp("2021-01-01")) & (row <=pd.Timestamp("2021-06-30")):
        return "S1 2021"    
    if (row > pd.Timestamp("2021-06-30")) & (row <=pd.Timestamp("2021-12-31")):
        return "S2 2021" 

df1['Année'] = df1['Item - Accounting Date'].apply(condition)

【讨论】:

  • 你为什么不简单地使用例如pd.Timestamp('2020-01-01') - 再次保持格式一致。
  • 我们可以/应该。我刚刚从 OP 的功能中删除了一些东西。实际上,我将进行编辑以更改为。谢谢
  • 嗨@Manlai,感谢您的帮助。不幸的是,我仍然有一个错误:TypeError: 'Timestamp' 类型的参数不可迭代 - 你知道如何解决它吗?
  • 我找到了解决方案 - 第二个条件将 str 与它不起作用的日期进行了比较!感谢大家的帮助
猜你喜欢
  • 2020-02-23
  • 1970-01-01
  • 1970-01-01
  • 2021-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-30
相关资源
最近更新 更多