在 pandas 中绕一列 [英] round a single column in pandas
问题描述
是否可以在不影响数据帧其余部分的情况下在熊猫中舍入单个列?
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) 给
df.value1.apply(np.round) gives
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
推荐答案
您非常亲密.
您已将回合应用于df.value1
给定的一系列值.
因此,返回类型为Series.
您需要将该系列分配回数据框(或具有相同索引的另一个数据框).
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).
此外,还有一个 pandas.Series.round
方法,基本上是pandas.Series.apply(np.round)
的简写.
Also, there is a pandas.Series.round
method which is basically a short hand for 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
这篇关于在 pandas 中绕一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!