pandas 使用 Python 删除带有数字和字符串的数据帧中的小数点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22983638/
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
Remove Decimal Point in a Dataframe with both Numbers and String Using Python
提问by Ian
I have a data Frame with about 50,000 records; and I noticed that ".0" have been added behind all numbers in a column. I have been trying to remove the ".0", so that the table below;
我有一个包含大约 50,000 条记录的数据框;我注意到在列中的所有数字后面都添加了“.0”。我一直试图删除“.0”,以便下表;
N | Movies
1 | Save the Last Dance
2 | Love and Other Drugs
3 | Dance with Me
4 | Love Actually
5 | High School Musical
6 | 2012.0 <-----
7 | Iron Man
8 | 300.0 <-----
9 | Inception
10 | 360.0 <-----
11 | Pulp Fiction
Will look like this;
看起来像这样;
N | Movies
1 | Save the Last Dance
2 | Love and Other Drugs
3 | Dance with Me
4 | Love Actually
5 | High School Musical
6 | 2012 <-----
7 | Iron Man
8 | 300 <-----
9 | Inception
10 | 360 <-----
11 | Pulp Fiction
The challenge is that the column contains both numbers and strings.
挑战在于该列同时包含数字和字符串。
Is this possible, if yes, how?
这是可能的,如果是,如何?
Thanks in advance.
提前致谢。
采纳答案by EdChum
Use a function and apply to whole column:
使用函数并应用于整列:
In [94]:
df = pd.DataFrame({'Movies':['Save the last dance', '2012.0']})
df
Out[94]:
Movies
0 Save the last dance
1 2012.0
[2 rows x 1 columns]
In [95]:
def trim_fraction(text):
if '.0' in text:
return text[:text.rfind('.0')]
return text
df.Movies = df.Movies.apply(trim_fraction)
In [96]:
df
Out[96]:
Movies
0 Save the last dance
1 2012
[2 rows x 1 columns]
回答by Nishant Nawarkhede
Here is hint for you ,
这是给你的提示,
In case of Valid number ,
在有效号码的情况下,
a="2012.0"
try:
a=float(a)
a=int(a)
print a
except:
print a
Output:
输出:
2012
In case of String like "Dance with Me"
如果像“与我共舞”这样的字符串
a="Dance with Me"
try:
a=float(a)
a=int(a)
print a
except:
print a
Output:
输出:
Dance with Me
回答by user3273866
Python 2.7.2+ (default, Jul 20 2012, 22:15:08)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> str1 = "300.0"
>>> str(int(float(str1)))
'300'
>>>

