[英]Remove Decimal Point in a Dataframe with both Numbers and String Using Python
I have a data Frame with about 50,000 records; 我有一个大约有50,000条记录的数据框; and I noticed that ".0" have been added behind all numbers in a column. 我注意到列中所有数字后面都添加了“.0”。 I have been trying to remove the ".0", so that the table below; 我一直试图删除“.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. 提前致谢。
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]
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
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'
>>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.