简体   繁体   English

Python Pandas:从现有列创建日期数据框

[英]Python pandas: create a dataframe of dates from existing columns

I have a pandas dataframe with a column for years and one for months. 我有一个pandas数据框,其中有一个列数年,一个列数月。 How can I create a new date column based on these two (I can assume day = 15). 如何基于这两个创建新的日期列(我可以假设day = 15)。

I tried the following: 我尝试了以下方法:

import pandas as pd
import numpy as np
import datetime  

df = pd.DataFrame()
df['year'] = np.arange(2000,2010)

df['mydate']= datetime.date( df['year'].apply(lambda x: int(x)) , 1 , 1)

but I get this error message: 但我收到此错误消息:

 df['mydate']= datetime.date( df['year'].apply(lambda x: int(x)) , 1 , 1) File "C:\\Anaconda\\lib\\site-packages\\pandas\\core\\series.py", 

line 77, in wrapper "cannot convert the series to {0}".format(str(converter))) TypeError: cannot convert the series to 第77行,在包装器中“无法将系列转换为{0}”。format(str(converter)))TypeError:无法将系列转换为

which I don't understand because I explictly convert x to int. 我不明白,因为我明确将x转换为int。

Thanks! 谢谢!

You can build another column based on the existing columns by using df.apply(fnc, axis=1) . 您可以使用df.apply(fnc, axis=1)在现有列的基础上构建另一列。

In your case this becomes: 在您的情况下,它将变为:

df = pd.DataFrame()
df['year'] = np.arange(2000,2010)
df['month'] = 6

df['date_time']= df.apply(lambda row :
                          datetime.date(row.year,row.month,15), 
                          axis=1)

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

相关问题 Python Pandas Dataframe:如何从数据框中的现有列表创建列? - Python Pandas Dataframe: How to create columns from existing list in dataframe? Python:从现有的熊猫数据框创建数据框 - Python : Create a dataframe from existing pandas dataframe Python熊猫通过对现有列进行分组来创建其他数据框列 - Python pandas create additional dataframe columns by grouping on existing column 使用 pandas/python 从 DataFrame 中的两个现有文本列创建一个新列 - Create a new column from two existing text columns in a DataFrame using pandas/python 从 4 个现有列创建一个新列(python pandas) - create a new column from 4 existing columns (python pandas) 从 3 个现有列创建一个新列(python pandas) - create a new column from 3 existing columns (python pandas) 使用 python pandas 从现有列创建一个新的地图列 - Create a new map column from existing columns using python pandas python pandas dataframe从其他列的单元格创建新列 - python pandas dataframe create new column from other columns' cells Python 和 Pandas:从数据帧的 2 列创建 3d 直方图 - Python & Pandas: Create a 3d histogram from 2 columns of a dataframe 在现有的sql表中创建新列,其中包含来自pandas Dataframe的额外列 - create new columns in existing sql table, with extra columns from pandas Dataframe
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM