pandas 根据浮点列是否为整数(`float.is_integer`)在由True、False填充的pandas df中创建新列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40370382/
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
Creating new column in pandas df populated by True,False depending on whether a float column is a whole number (`float.is_integer`)
提问by user
I have a pandas df
where df['value']
is a series of floats.
我有一只Pandasdf
,那里df['value']
有一系列的花车。
- Some of the floats will be whole numbers (like 25.0). I want to create a new column,
df['is_it_whole'][i]
with values1
(orTrue
) is the correspondingdf['value'][i]
is a whole number,0
orFalse
otherwise. - I know I can do a for loop, but I am wondering if there is any trick I can use to do it fast (I have a large df).
- I tried using
df['is_it_whole'] = df['value'].is_integer()
but pandas series do not support theis_integer
method, I am looking for something similar that would work.
- 一些浮点数将是整数(如 25.0)。我想创建一个新的列,
df['is_it_whole'][i]
其值1
(或True
)被相应的df['value'][i]
是一个整数,0
或False
以其他方式。 - 我知道我可以做一个 for 循环,但我想知道是否有任何技巧可以用来快速完成(我有一个很大的 df)。
- 我尝试使用
df['is_it_whole'] = df['value'].is_integer()
但Pandas系列不支持该is_integer
方法,我正在寻找类似的方法。
Suggestions?
建议?
回答by Dennis Golomazov
import pandas as pd
df = pd.DataFrame([['A', 1], ['B', 2.5], ['C', 3.0], ['D', 3.2]], columns=['label', 'value'])
df['is_it_whole'] = df['value'].map(lambda x: x.is_integer())
df
label value is_it_whole
0 A 1.0 True
1 B 2.5 False
2 C 3.0 True
3 D 3.2 False
回答by Psidom
You can try:
你可以试试:
df['is_it_whole'] = (df['value'].round() == df['value'])
Or to take into account float number inaccuracy:
或者考虑浮点数不准确:
tol = 0.001
df['is_it_whole'] = ((df['value'].round() - df['value']).abs() < tol)
回答by simon
This applies is_integer to each element in the series:
这将 is_integer 应用于系列中的每个元素:
df['is_it_whole'] = df['value'].apply(lambda x: x.is_integer())
回答by smci
You don't need to declare a lambda function. Just directly apply df['value'].map(float.is_integer)
您不需要声明 lambda 函数。直接申请就行df['value'].map(float.is_integer)
import pandas as pd
df = pd.DataFrame([['A', 1], ['B', 2.5], ['C', 3.0], ['D', 3.2]], columns=['label', 'value'])
df['is_it_whole'] = df['value'].map(float.is_integer)
>>> df
label value is_it_whole
0 A 1.0 True
1 B 2.5 False
2 C 3.0 True
3 D 3.2 False