Python 有没有一种方法可以有效地转换数据帧中的数据类型';谁的专栏?
数据帧Python 有没有一种方法可以有效地转换数据帧中的数据类型';谁的专栏?,python,pandas,dataframe,Python,Pandas,Dataframe,数据帧df有一列名为LastPrice。每个df['LastPrice']都是一个字符串,我想将字符串转换为浮点。我使用map来解决它 #-*- encoding:utf-8 -*- import pandas as pd from pandas import Series,DataFrame df = DataFrame({'Time':['1-14','1-15','1-16'],'LastPrice':['1.0','2.0','3.0']},columns = ['Time','Las
df
有一列名为LastPrice
。每个df['LastPrice']
都是一个字符串
,我想将字符串
转换为浮点
。我使用map
来解决它
#-*- encoding:utf-8 -*-
import pandas as pd
from pandas import Series,DataFrame
df = DataFrame({'Time':['1-14','1-15','1-16'],'LastPrice':['1.0','2.0','3.0']},columns = ['Time','LastPrice'])
f_L = df['LastPrice'].map(float)
print type(f_L[0])
print type(df['LastPrice'][0])
结果是:
<type 'numpy.float64'>
<type 'str'>
[Finished in 1.2s]
有没有一种方法可以有效地转换数据帧列中的数据类型?
我的意思是就地转换数据类型,而不是重新分配。您可以用于pandas
version>=0.17.0
:
pd.to_numeric(df['LastPrice'])
In [110]: pd.to_numeric(df['LastPrice'])
Out[110]:
0 1
1 2
2 3
Name: LastPrice, dtype: float64
在版本中,您可以尝试:
df['LastPrice']=df['LastPrice'].astype(float)
df=数据帧({'Time':['1-14','1-15','1-16'],'LastPrice':['1.0','2.0','3.0'],
列=[“时间”,“最后价格])
df['LastPrice']=df['LastPrice'].astype(浮动)
打印df
时间最后价格
0 1-14 1
1 1-15 2
2 1-16 3
打印类型(df['LastPrice'][0])
我有时使用自定义函数
def str_to_flt(s):
try:
return float(s)
except ValueError:
return None
然后我使用自定义函数
df['FloatField']=df['StrField'].apply(str_to_flt)
然后,我可以识别设置为NaN的“坏”值
希望这有帮助
df['LastPrice'] = df['LastPrice'].astype(float)
df = DataFrame({'Time':['1-14','1-15','1-16'],'LastPrice':['1.0','2.0','3.0']},
columns = ['Time','LastPrice'])
df['LastPrice'] = df['LastPrice'].astype(float)
print df
Time LastPrice
0 1-14 1
1 1-15 2
2 1-16 3
print type(df['LastPrice'][0])
<type 'numpy.float64'>
def str_to_flt(s):
try:
return float(s)
except ValueError:
return None
df['FloatField']=df['StrField'].apply(str_to_flt)