Python:将函数应用于数据框列,并将结果放入另一列

时间:2017-04-11 09:00:39

标签: python pandas dataframe machine-learning

您好我想应用下面的功能,将日期分为几个月和几年。我还想将这些结果导出到另一个名为'month'和'year'的列。第二部分是我遇到问题的地方,它将结果导出到另一列的行。谢谢。

'Full Date' 'Month'  'Year'

07/31/2016    07      2016
05/28/2011    05      2011

3 个答案:

答案 0 :(得分:3)

假设FullDate列属于datetime dtype:

In [119]: df['Month'] = df['FullDate'].dt.month

In [120]: df['Year'] = df['FullDate'].dt.year

In [121]: df
Out[121]:
    FullDate  Month  Year
0 2016-07-31      7  2016
1 2011-05-28      5  2011

如果是stringobject):

In [133]: df[['Month','Year']] = df['FullDate'].str.split('/', expand=True).loc[:, [0,2]]

In [134]: df
Out[134]:
     FullDate Month  Year
0  07/31/2016    07  2016
1  05/28/2011    05  2011

答案 1 :(得分:2)

另一种方法可以做到:

df = pd.DataFrame({'FullDate': ['07/31/2016','05/28/2011']})
df['Month'] = df['FullDate'].apply(lambda x: x.split('/')[0])
df['Year'] = df['FullDate'].apply(lambda x: x.split('/')[2])

答案 2 :(得分:1)

更详细的方法:

df = pd.DataFrame({'Full Date': ['07/31/2016','05/28/2011']})
def date_breaker(date):
    year = date[-4:]
    month = date[:2]
    return (year,month)
x = df['Full Date'].map(lambda x: date_breaker(x))
df['year'],df['month'] = zip(*x)