Python 围绕熊猫中的单列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26133538/
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-08-19 00:08:32  来源:igfitidea点击:

round a single column in pandas

pythonpandas

提问by k3it

Is there a way to round a single column in pandas without affecting the rest of the dataframe?

有没有办法在不影响数据帧的其余部分的情况下舍入熊猫中的单个列?

 df:
      item  value1  value2
    0    a    1.12     1.3
    1    a    1.50     2.5
    2    a    0.10     0.0
    3    b    3.30    -1.0
    4    b    4.80    -1.0

df.value1.apply(np.round) gives

df.value1.apply(np.round) 给出

0    1
1    2
2    0
3    3
4    5
5    5

What is the correct way to make data look like this:

使数据看起来像这样的正确方法是什么:

  item  value1  value2
0    a       1     1.3
1    a       2     2.5
2    a       0     0.0
3    b       3    -1.0
4    b       5    -1.0
5    c       5     5.0

采纳答案by Lyndon White

You are very close. You applied the round to the series of values given by df.value1. The return type is thus a Series. You need to assign that series back to the dataframe (or another dataframe with the same Index).

你很亲近。您将舍入应用于由 给出的一系列值df.value1。因此返回类型是一个系列。您需要将该系列分配回数据帧(或具有相同索引的另一个数据帧)。

Also, there is a pandas.Series.roundmethod which is basically a short hand for pandas.Series.apply(np.round).

此外,还有一种pandas.Series.round方法基本上是pandas.Series.apply(np.round).

In[2]: 
    df.value1 = df.value1.round()
    print df

Out[2]:
    item  value1  value2
    0    a       1     1.3
    1    a       2     2.5
    2    a       0     0.0
    3    b       3    -1.0
    4    b       5    -1.0

回答by Reimar

For some reason the round() method doesn't work if you have float numbers with many decimal places, but this will.

出于某种原因,如果您有许多小数位的浮点数,则 round() 方法不起作用,但这会。

decimals = 2    
df['column'] = df['column'].apply(lambda x: round(x, decimals))

回答by Premal

No need to use for loop. It can be directly applied to a column of a dataframe

无需使用 for 循环。它可以直接应用于数据框的列

sleepstudy['Reaction'] = sleepstudy['Reaction'].round(1)

回答by Siddi

Use the pandas.DataFrame.round()method like this:

像这样使用pandas.DataFrame.round()方法:

df = df.round({'value1': 0})

Any columns not included will be left as is.

未包含的任何列将保持原样。

回答by kawingkelvin

If you are doing machine learning and use tensorflow, many float are of 'float32', not 'float64', and none of the methods mentioned in this thread likely to work. You will have to first convert to float64 first.

如果您正在进行机器学习并使用 tensorflow,则许多浮点数是“float32”,而不是“float64”,并且此线程中提到的方法都不可能有效。您必须先转换为 float64。

x.astype('float')

before round(...).

在回合之前(...)。