【问题标题】:Months in Pandas熊猫的几个月
【发布时间】:2019-03-29 11:48:30
【问题描述】:

我想在 dataFrame 中创建一个列,这将是另外两个结果的结果

在下面的示例中,创建了两个数据帧:df1 和 df2。

然后创建了第三个dataFrame,它是前两个的交汇点。在此 df3 中,“日期”列已更改为 dateTime 类型。

之后,“DateMonth”列被创建,其月份是从“Dates”列中提取的。

# df1 and df2:
id_sales   = [1, 2, 3, 4, 5, 6]
col_names  = ['Id', 'parrotId', 'Dates']
df1        = pd.DataFrame(columns = col_names)
df1.Id     = id_sales
df1.parrotId = [1, 2, 3, 1, 2, 3]
df1.Dates  = ['2012-12-25', '2012-08-20', '2013-07-23', '2014-01-14', '2016-02-21', '2015-10-31']

col_names2 = ['parrotId', 'months']
df2        = pd.DataFrame(columns = col_names2)
df2.parrotId = parrot_id
df2.months = [0, ('Fev, Mar, Apr'), 0]

# df3
df3 = pd.merge(df1, df2, on = 'parrotId')
df3.Dates = pd.to_datetime(df3.Dates)
df3['DateMonth'] = df3.Dates.dt.month

在这个 df3 中,我需要一个新列,如果“月”列中存在“DateMonth”列的月份,则该列的值将为 1。

我的困难是在“月份”列中或者值为零或者值是月份列表。

如何实现这个结果?

【问题讨论】:

  • 什么是 parrot_id?

标签: python pandas datetime dataframe


【解决方案1】:

尝试以下解决方案:

import pandas as pd

# define function for df.apply
def matched(row):
    if type(row['months'])==str:
        # for the case ('Feb, Mar, Apr') - get numerical representation of month from your string and return True if the 'Dates' value matches with some list item
        return row['Dates'].month in [datetime.strptime(mon.strip(), '%b').month for mon in row['months'].split(',')]  
    else:
        # for numbers - return True if months match
        return row['Dates'].month==row['months']

# df1 and df2:
id_sales   = [1, 2, 3, 4, 5, 6]
col_names  = ['Id', 'parrotId', 'Dates']
df1        = pd.DataFrame(columns = col_names)
df1.Id     = id_sales
df1.parrotId = [1, 2, 3, 1, 2, 3]
df1.Dates  = ['2012-12-25', '2012-08-20', '2013-07-23', '2014-01-14', '2016-02-21', '2015-10-31']

col_names2 = ['parrotId', 'months']
df2        = pd.DataFrame(columns = col_names2)
df2.parrotId = [1, 2, 3]
df2.months = [12, ('Feb, Mar, Apr'), 0]

df3 = pd.merge(df1, df2, on = 'parrotId')
df3.Dates = pd.to_datetime(df3.Dates)

# use apply to run the function on each row, astype converts boolean to int (0/1) 
df3['DateMonth'] = df3.apply(matched, axis=1).astype(int)
df3

Output:      
Id  parrotId    Dates   months          DateMonth
0   1   1   2012-12-25  12              1
1   4   1   2014-01-14  12              0
2   2   2   2012-08-20  Feb, Mar, Apr   0
3   5   2   2016-02-21  Feb, Mar, Apr   1
4   3   3   2013-07-23  0               0
5   6   3   2015-10-31  0               0

【讨论】:

  • Lukas,首先,非常感谢您的帮助。不幸的是,它没有用。我收到一条错误消息:“名称‘日期时间’未定义”。当我收到一条新的错误消息时,我什至导入了 datetime 库并再次运行最后一步:“AttributeError: ('module' datetime 'has no attribute' strptime '",'发生在索引 2 ')”。
  • 第一次尝试时,我错误地导入了库。我以这种方式导入它并且它运行良好:从日期时间导入日期时间。再次感谢 Lukas。
  • Lukas,您对如何解决以下错误有任何意见吗? ValueError: ('未转换的数据仍然存在:t', '发生在索引 16772')
  • @Ângelo,我猜某个月份的缩写有错别字。当我做这样的事情时:df2.months = [12, ('Febt, Mar, Apr'), 0],我得到类似的错误(只是错误索引不同)。如果您从某个文件中读取源数据,请浏览并尝试找到不正确的月份缩写。格式(可能有 4 个字符并以 t 结尾)。
猜你喜欢
  • 2013-07-01
  • 1970-01-01
  • 2023-03-09
  • 1970-01-01
  • 2017-08-22
  • 2018-01-31
  • 2018-11-24
  • 2019-08-24
  • 1970-01-01
相关资源
最近更新 更多