皮洪(Pyrhon):获取当前月份的当前日期?

时间:2020-05-25 13:57:07

标签: python pandas dataframe

我有两列数字和日期的df。如果dayTrue,我想获取特定日子的频率。

根据日历从Monday - 0sunday - 6

对于1(Tuesday),在4 Tuesdays的月份中有may个。 同样,6(Sunday)5 Sundays中有may

df

    df= pd.DataFrame(data = {'number' : ['1', '2', '3', '4', '6'], 'day' : [True, False, False, False, True]}) 


        number  day
    0   1       True
    1   2       False
    2   3       False
    3   4       False
    4   6       True

我的例外输出:

        number          day
    0   7,14,21,28      True
    1   2               False   
    2   3               False
    3   4               False
    4   3,10,17,24,31   True

2 个答案:

答案 0 :(得分:1)

让我们尝试Calendar

from calendar import Calendar
a=np.array(Calendar().monthdayscalendar(2020,5))
l=[','.join(a[:,int(x)][a[:,int(x)]!=0].astype(str)) if y else x for x, y  in zip(df.number,df.day)]
['5,12,19,26', '2', '3', '4', '3,10,17,24,31']
df['number']=l

答案 1 :(得分:0)

我的解决方案比其他方法更通用,即,它可以计算天数 当前月份,只要您运行此代码即可。

从一些预备计算开始:

# Start of the current month
dStart = pd.offsets.MonthBegin(0).rollback(pd.Timestamp.today().normalize())
# DataFrame for the current month, for now only "Date" column
mnth = pd.DataFrame({'Date': pd.date_range(start=dStart,
    periods=dStart.daysinmonth)})
# Add "Day of Week" column
mnth['DoW'] = mnth.Date.dt.dayofweek
# Add "Day" column (as string)
mnth['Day'] = mnth.Date.dt.day.astype(str)
# Convert to list of days (for each DoW)
mnth = mnth.groupby('DoW').Day.apply(lambda s: ','.join(list(s)))

要有条件地更改 df 中的每个数字,足以运行 单条说明:

df.number = df.apply(lambda row: mnth.loc[int(row.number)]
    if row.day else row.number, axis=1)

到2020年5月的结果是:

          number    day
0     5,12,19,26   True
1              2  False
2              3  False
3              4  False
4  3,10,17,24,31   True