对 Pandas 数据框中一列的每条记录应用相同的函数

Apply the same function on each record of a column in Pandas dataframe

我有一个包含特定格式的日期时间列的数据集。我需要从此列中创建新功能,这意味着我需要通过从上述日期时间列中提取信息来向数据框添加新列。我的示例输入数据框列如下所示。

id    datetime         feature2
1    12/3/2020 0:56       1
2    11/25/2020 13:26     0

预期输出为:

id    date      hour    mints    feature2
1    12/3/2020   0       56         1
2    11/25/2020  13      26         0

Pandas apply() 方法可能不适用于此,因为添加了新列。最好的方法是什么?

有什么方法可以在列的每个记录上应用单个函数来通过在整个列上应用来实现这一点?

IICU

df.date=pd.to_datetime(df.date)
df.set_index(df.date, inplace=True)
df['hour']=df.index.hour
df['mints']=df.index.minute

pandas系列.dt存取器

  • 您的日期时间数据来自 pandas 列(系列),因此请使用 .dt accessor
import pandas as pd

df = pd.DataFrame({'id': [1, 2],
                   'datetime': ['12/3/2020 0:56', '11/25/2020 13:26'],
                   'feature2': [1, 0]})
df['datetime'] = pd.to_datetime(df['datetime'])

 id            datetime  feature2
  1 2020-12-03 00:56:00         1
  2 2020-11-25 13:26:00         0

# create columns
df['hour'] = df['datetime'].dt.hour
df['min'] = df['datetime'].dt.minute
df['date'] = df['datetime'].dt.date

# final
 id            datetime  feature2  hour  min        date
  1 2020-12-03 00:56:00         1     0   56  2020-12-03
  2 2020-11-25 13:26:00         0    13   26  2020-11-25