我想输入df一个函数,调用输出另一个数据帧“df_fn”,并且df保持不变。我怎么做?
我的代码要么什么也不做df_fn等于df或df_fn并且df都改变了。
使用 df_fn[cols][df_fn.fuel_type != 'gas'] = np.nan
import pandas as pd
import numpy as np
df = pd.DataFrame({'n_wheels': [2, 4, 4],
'color': ['red', 'blue', 'red'],
'year': [2010, 1990, 1999],
'fuel_type': ['diesel', 'gas', 'electric']})
print('df = \n', df)
def fn(df_fn):
cols = ['n_wheels', 'color', 'year']
# df_fn.loc[df_fn.fuel_type != 'gas', cols] = np.nan
df_fn[cols][df_fn.fuel_type != 'gas'] = np.nan
return df_fn
new_df = fn(df)
print('df = \n', df)
print('new_df = \n', new_df)
输出:
df =
n_wheels color year fuel_type
0 2 red 2010 diesel
1 4 blue 1990 gas
2 4 red 1999 electric
df =
n_wheels color year fuel_type
0 2 red 2010 diesel
1 4 blue 1990 gas
2 4 red 1999 electric
new_df =
n_wheels color year fuel_type
0 2 red 2010 diesel
1 4 blue 1990 gas
2 4 red 1999 electric
使用 df_fn.loc[df_fn.fuel_type != 'gas', cols] = np.nan
print('df = \n', df)
def fn(df_fn):
cols = ['n_wheels', 'color', 'year']
# df_fn[cols][df_fn.fuel_type != 'gas'] = np.nan
df_fn.loc[df_fn.fuel_type != 'gas', cols] = np.nan
return df_fn
new_df = fn(df)
print('df = \n', df)
print('new_df = \n', new_df)
输出:
df =
n_wheels color year fuel_type
0 2 red 2010 diesel
1 4 blue 1990 gas
2 4 red 1999 electric
df =
n_wheels color year fuel_type
0 NaN NaN NaN diesel
1 4.0 blue 1990.0 gas
2 NaN NaN NaN electric
new_df =
n_wheels color year fuel_type
0 NaN NaN NaN diesel
1 4.0 blue 1990.0 gas
2 NaN NaN NaN electric
慕桂英4014372
相关分类