pandas 熊猫数据框中的圆列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31247763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:34:41  来源:igfitidea点击:

Round columns in pandas dataframe

pythonpandas

提问by kamome

I have got the following pandas data frame

我有以下Pandas数据框

          Y         X id WP_NER
0 35.973496 -2.734554  1  WP_01 
1 35.592138 -2.903913  2  WP_02 
2 35.329853 -3.391070  3  WP_03 
3 35.392608 -3.928513  4  WP_04 
4 35.579265 -3.942995  5  WP_05 
5 35.519728 -3.408771  6  WP_06 
6 35.759485 -3.078903 7 WP_07 

I′d like to round Y and X columns using pandas. How can I do that ?

我想使用 Pandas 对 Y 和 X 列进行四舍五入。我怎样才能做到这一点 ?

回答by Zero

You can now, use roundon dataframe

您现在可以round在数据框上使用

Option 1

选项1

In [661]: df.round({'Y': 2, 'X': 2})
Out[661]:
       Y     X  id WP_NER
0  35.97 -2.73   1  WP_01
1  35.59 -2.90   2  WP_02
2  35.33 -3.39   3  WP_03
3  35.39 -3.93   4  WP_04
4  35.58 -3.94   5  WP_05
5  35.52 -3.41   6  WP_06
6  35.76 -3.08   7  WP_07

Option 2

选项 2

In [662]: cols = ['Y', 'X']

In [663]: df[cols] = df[cols].round(2)

In [664]: df
Out[664]:
       Y     X  id WP_NER
0  35.97 -2.73   1  WP_01
1  35.59 -2.90   2  WP_02
2  35.33 -3.39   3  WP_03
3  35.39 -3.93   4  WP_04
4  35.58 -3.94   5  WP_05
5  35.52 -3.41   6  WP_06
6  35.76 -3.08   7  WP_07

回答by EdChum

You can applyround:

你可以:applyround

In [142]:
df[['Y','X']].apply(pd.Series.round)

Out[142]:
    Y  X
0  36 -3
1  36 -3
2  35 -3
3  35 -4
4  36 -4
5  36 -3
6  36 -3

If you want to apply to a specific number of places:

如果您想申请特定数量的名额:

In [143]:
df[['Y','X']].apply(lambda x: pd.Series.round(x, 3))

Out[143]:
        Y      X
0  35.973 -2.735
1  35.592 -2.904
2  35.330 -3.391
3  35.393 -3.929
4  35.579 -3.943
5  35.520 -3.409
6  35.759 -3.079

EDITYou assign the above to the columns you want to modify like the following:

编辑您将上述内容分配给要修改的列,如下所示:

In [144]:
df[['Y','X']] = df[['Y','X']].apply(lambda x: pd.Series.round(x, 3))
df

Out[144]:
        Y      X  id WP_NER
0  35.973 -2.735   1  WP_01
1  35.592 -2.904   2  WP_02
2  35.330 -3.391   3  WP_03
3  35.393 -3.929   4  WP_04
4  35.579 -3.943   5  WP_05
5  35.520 -3.409   6  WP_06
6  35.759 -3.079   7  WP_07