我目前正在使用一些 DataFrame,并希望使我的代码模块化。这需要将数据帧传递给函数。我知道 DataFrame 的可变性质以及将可变实例传递给函数时的一些“陷阱”。DataFrames 的功能是否有最佳实践?我应该在函数内复制一份然后将其传回吗?或者我应该在函数内对 df 进行更改并返回 None ?
选项 1 还是选项 2 更好?下面是传达这个想法的基本代码:
选项1:
def test(df):
df['col1'] = df['col1']+1
return None
test(df)
Run Code Online (Sandbox Code Playgroud)
选项2:
def test(main_df):
df = main_df.copy()
df['col1'] = df['col1']+1
return df
main_df = test(main_df)
Run Code Online (Sandbox Code Playgroud) 我有一个 DataFrames 字典,其中的键是指数据的年份。我想遍历字典并对数据帧进行修改。我对 dfs 的列名和内容进行了修改。
for year, df in df_data.items():
cols = df .columns
new_cols = [re.sub(r'\s\d{4}\-\d{2}', '', c) for c in cols]
df.columns = new_cols
for year, df in df_data.items():
df['Date'] = pd.to_datetime(df['Date'], infer_datetime_format=True)
df = df.drop_duplicates(subset='Id', keep='first')
Run Code Online (Sandbox Code Playgroud)
有人可以向我解释这样做的行为吗?特别是 dfs 如何存储在内存中以及为什么列的重命名有效但对内容的修改无效。另外,有没有最好的方法来做到这一点,要么复制 df,然后在 dict 索引中替换它,要么不断更改 df_data[year] 引用?