对于这个特殊的问题,我不能想出如何处理这个问题的逻辑或流程,我需要一些帮助。
给定两个数据帧,分别以季度和半年表示
df1:季度(由月份开始表示)
ID Date Volume
1 2020-04 2
1 2020-07 5
1 2020-10 1
1 2021-01 8df2:半年(以月份开始表示)
ID Date Volume
1 2020-07 7
1 2021-01 9
2 2019-07 11
2 2020-01 14有没有一种方法可以让python(pandas)检测出它们是由月份结束还是月份开始表示的?
如果用月份开始表示,则始终转换为月份结束。如果用month end表示,则不做任何更改。
在本例中,两者都将转换为月份开始,因此dataframe如下所示:
预期输出:
df1:季度
ID Date Volume
1 2020-03 2
1 2020-06 5
1 2020-9 1
1 2020-12 8df2:半年
ID Date Volume
1 2020-06 7
1 2020-12 9
2 2019-06 11
2 2019-12 14这可以使用pd.OffSets(months=x)轻松完成。这里的主要挑战是python是否能够检测月末和月初。
发布于 2021-04-28 20:45:14
这里有一种可能的方法:
import pandas as pd
df = pd.DataFrame({'ID': {0: 1, 1: 1, 2: 2, 3: 2},
'Date': {0: '2020-07', 1: '2021-01', 2: '2019-07', 3: '2020-01'},
'Volume': {0: 7, 1: 9, 2: 11, 3: 14},
'source': {0: 'half_y', 1: 'half_y', 2: 'half_y', 3: 'half_y'}})
df['Date'] = pd.to_datetime(df['Date'], format='%Y-%m')
df['Quarter'] = df['Date'].dt.quarter
df['Half_year'] = (df['Quarter'] > 1)*1熊猫甚至比这更强大:
查看左侧的here,所有条目都以: pandas.Series.dt开头。
所以我们甚至可以得到这样的结果:
df['Date'].dt.is_month_start
df['Date'].dt.is_month_end或
df['Date'].is_quarter_start
df['Date'].is_quarter_end您还可以使用简单的映射:
import pandas as pd
df = pd.DataFrame({'ID': [1, 1, 1, 1, 1, 1, 1, 1],
'Date': ['2020-04',
'2020-07',
'2020-10',
'2021-01',
'2020-04',
'2020-07',
'2020-10',
'2021-01'],
'Volume': [2, 5, 1, 8, 2, 5, 1, 8],
'source': ['quarter',
'quarter',
'quarter',
'quarter',
'half_y',
'half_y',
'half_y',
'half_y']})
df['Date'] = pd.to_datetime(df['Date'], format='%Y-%m')
df['Month'] = df['Date'].dt.month
df_map = pd.DataFrame({'Month': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
'Quarter': [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4],
'Trimester': [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3]})
df.merge(df_map, on=['Month'])https://stackoverflow.com/questions/67300184
复制相似问题