Python 使用日期列值的日期范围创建数据框
给定以下数据帧: 人 2018-01 2018-02 2018-03 2018-04 2018-05 2018-06 2018-07 p1 Y Y Y Y Y p2 Y Y Y YPython 使用日期列值的日期范围创建数据框,python,pandas,Python,Pandas,给定以下数据帧: 人 2018-01 2018-02 2018-03 2018-04 2018-05 2018-06 2018-07 p1 Y Y Y Y Y p2 Y Y Y Y 假设您正在从excel加载数据: import pandas as pd # Input data prep data = pd.read_excel('data.xlsx') data = data.T data.reset_index(inplace=True) # Setting the proper he
假设您正在从excel加载数据:
import pandas as pd
# Input data prep
data = pd.read_excel('data.xlsx')
data = data.T
data.reset_index(inplace=True)
# Setting the proper header
new_header = data.iloc[0]
data = data[1:]
data.columns = new_header
# Easy to work with 1 and 0 for consecutives with cumsum
data = data.fillna(0)
data = data.replace("y", 1)
df_result = pd.DataFrame() # Store your desired table
for column in data.columns[1:]: # per person iteration
df_temp = data[["person", column]]
df_temp['consecutive'] = (df_temp[column].diff(1) != 0).cumsum()
df_temp = df_temp[df_temp[column] > 0]
df_temp = pd.DataFrame({
'person': column,
'start_date': df_temp.groupby('consecutive')["person"].first(),
'end_date': df_temp.groupby('consecutive')["person"].last()
}).reset_index(drop=True)
df_result = df_result.append(df_temp)
# First and last day of month
df_result['start_date'] = df_result['start_date'].values.astype('datetime64[M]')
df_result['end_date'] = pd.to_datetime(df_result['end_date']) + MonthEnd(1)
print(df_result)
请正确设置您的问题的格式。很抱歉,该表在预览中看起来很好。谢谢@Paul HHey,您的返回数据在第二行是错误的。由于连续几个月,p2的结束日期应为2018年5月31日。