Skip to main content
 首页 » 编程设计

使用时间片的python变量赋值

2025年04月02日15xxx_UU

这更像是一个新手 python 问题。我有一个 pandas 数据帧 tmp_df,我使用 3 个日期时间输入对其进行切片,如下所示以提取不同时间范围的数据:

tmp_daily_df = tmp_df.loc[idx[daily[1]:daily[2]],:] 
tmp_weekly_df = tmp_df.loc[idx[weekly[1]: weekly[2]],:] 
tmp_monthly_df = tmp_df.loc[idx[monthly[1]: monthly[2]],:] 

然后我将生成的 3 个数据帧传递给一个名为 compute_stats() 的函数,该函数计算各种统计数据并对输入数据帧(即 tmp_daily_df)执行一些操作。一种这样的操作是向 tmp_daily_df 等添加几个新列。

final_daily_df = compute_stats(tmp_daily_df, 'M','').reset_index(drop=True) 
final_weekly_df = compute_stats(tmp_weekly_df, 'M','').reset_index(drop=True) 
final_monthly_df = compute_stats(tmp_monthly_df, 'M','').reset_index(drop=True) 

我的问题是因为 python 变量赋值更像是一个链接而不是一个副本我想知道对 compute_stats 的第二次和第三次调用是否会被对 tmp_daily_df 的操作破坏,这是 tmp_df 的一个时间片,被 tmp_weekly_df 和tmp_monthly_df.

请您参考如下方法:

切片列表会创建一个副本,换句话说:

new_list = l[:] 

相当于:

new_list = list(l) 

DataFrames 的工作方式有点不同。 看看这篇文章: dataframes copies vs views

当与标量索引/切片一起使用时,DataFrame.loc 将返回一个 View 。

根据这个:

Whenever an array of labels or a boolean vector are involved in the indexing operation, the result will be a copy. With single label / scalar indexing and slicing, e.g. df.ix[3:6] or df.ix[:, 'A'], a view will be returned.

除非您使用标签数组或 bool 向量,否则您将获得一个 View 。 使用复制方法会给你想要的结果。