我正在使用SQLAlchemy和MySQL创建一个ORM。 我用以下方法自动映射了数据库表:
# read in your data
df = pd.DataFrame.from_records([
[np.nan,7.5,30.0,np.nan,7.5,30.0,7.5,np.nan,np.nan,7.5,7.5,np.nan,np.nan]],
columns=['Mar_x','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec','Jan','Feb','Mar_y'])
# function to return the new, upgrade, downgrade, etc
def value_comparison(diff):
if diff==0:
return 'E'
elif diff > 0:
return 'U'
elif diff < 0:
return 'D'
else:
return 'N'
# get the forward difference in time
df_diff = df.ffill(axis=1).diff(axis=1)
# apply the map to return your states
df_results = df_diff.apply(lambda row: row.apply(value_comparison), axis=1)
# correct for the NaN states where the forward difference was not defined
df_results[df.isna()]= np.nan
# correct for the case when the user cancels
mask = (df.isna() & ~df.shift(1, axis=1).isna())
df_results[mask] = 'C'
# correct for renew
mask = (~df.isna() & df.shift(1, axis=1).isna())
df_results[mask[mask == True].cumsum(axis=1) > 1] = 'Renew'
# result
print(df_results)
场景有时间表,但有限制。 然后在某个时候创建该对象:
Mar_x Apr May Jun Jul Aug Sep Oct Nov Dec Jan Feb Mar_y
0 NaN N U C Renew U D C NaN Renew E C NaN
我可以访问所有 table_schedule 列并正常设置它们,如下所示:
Base = automap_base()
Base.prepare(engine, reflect=True)
tScenario = Base.classes.table_scenario
tSchedule = Base.classes.table_schedule
tScheduleRestriction = Base.classes.table_schedule_restriction
但是,如果我要访问联接表( table_schedule_restriction )中的列,则该列将被埋在其中:
schedule = (session
.query(tSchedule)
.join(tScheduleRestriction)
.filter(and_(
tSchedule.scenario_id==47,
tSchedule.period=='saturday')
)
.all()
)
我的问题是:如何从两个表中获取所有列作为计划对象的直接属性?
我知道一种方法是在.query内部的两个表中声明所有列,例如伪代码:
“。query( tSchedule.parameter01,tScheduleRestriction.parameter01_min 等)”
但是我认为有更好的方法。
感谢您的关注。