我正在尝试在数据框中舍入两列。但是,我得到的结果与原始结果相同。代码如下:
def lonlat_round(dataframe, decimal_places):
dataframe[['lon','lat']] = dataframe[['lon','lat']].apply(pd.to_numeric)
dataframe['lon'] = dataframe['lon'].round(decimal_places)
dataframe['lat'] = dataframe['lat'].round(decimal_places)
return dataframe
dat = pd.DataFrame({'lon': [1.1, 2.2, 3.3], 'lat': [5.5, 6.6, 7.7]})
dat_new = lonlat_round(dataframe=dat, decimal_places=0)
dat_new == dat
它显示所有真实......为什么会这样?如何更改值而不是外观?谢谢!
答案 0 :(得分:2)
您在函数中使用了引用,因此当您调用round
时,您还修改了传入的df:
In [7]:
dat
Out[7]:
lat lon
0 6 1
1 7 2
2 8 3
In [10]:
dat_new
Out[10]:
lat lon
0 6 1
1 7 2
2 8 3
如果您使用传入的df copy()
,则会看到现在所有值的比较显示为False
:
In [11]:
def lonlat_round(df, decimal_places):
dataframe = df.copy()
dataframe[['lon','lat']] = dataframe[['lon','lat']].apply(pd.to_numeric)
dataframe['lon'] = dataframe['lon'].round(decimal_places)
dataframe['lat'] = dataframe['lat'].round(decimal_places)
return dataframe
dat = pd.DataFrame({'lon': [1.1, 2.2, 3.3], 'lat': [5.5, 6.6, 7.7]})
dat_new = lonlat_round(df=dat, decimal_places=0)
dat_new == dat
Out[11]:
lat lon
0 False False
1 False False
2 False False
答案 1 :(得分:0)
您可以尝试这种方法。
import pandas as pd
dat = pd.DataFrame({'lon': [1.1, 2.2, 3.3], 'lat': [5.5, 6.6, 7.7]})
#determine the columns and the corresponding round scale by a dictionary
dat = dat.round({'lon': 0, 'lat': 0})
结果将是:
dat=
lat lon
0 6.0 1.0
1 7.0 2.0
2 8.0 3.0