Pandas数据帧将特定列从字符串转换为float

时间:2015-10-29 21:09:20

标签: python pandas

我正在尝试对Kenneth法国行业组合进行一些简单的分析(第一次使用Pandas / Python),数据采用txt格式(参见代码中的链接)。在我可以进行计算之前,首先要正确地将它加载到Pandas数据框中,但我已经在这几个小时内一直在努力:

import urllib.request
import os.path
import zipfile
import pandas as pd
import numpy as np

# paths
url = 'http://mba.tuck.dartmouth.edu/pages/faculty/ken.french/ftp/48_Industry_Portfolios_CSV.zip'
csv_name = '48_Industry_Portfolios.CSV'
local_zipfile = '{0}/data.zip'.format(os.getcwd())
local_file = '{0}/{1}'.format(os.getcwd(), csv_name)

# download data
if not os.path.isfile(local_file):
    print('Downloading and unzipping file!')
    urllib.request.urlretrieve(url, local_zipfile)
    zipfile.ZipFile(local_zipfile).extract(csv_name, os.path.dirname(local_file))

# read from file
df = pd.read_csv(local_file,skiprows=11)
df.rename(columns={'Unnamed: 0' : 'dates'}, inplace=True)

# build new dataframe
first_stop = df['dates'][df['dates']=='201412'].index[0]
df2 = df[:first_stop]

# convert date to datetime object
pd.to_datetime(df2['dates'], format = '%Y%m')
df2.index = df2.dates

除日期外,所有列均代表财务回报。但是,由于文件格式化,这些现在是字符串。根据熊猫文档,这应该可以解决问题:

df2.convert_objects(convert_numeric=True)

但是列仍然是字符串。其他建议是循环列(请参阅例如pandas convert strings to float for multiple columns in dataframe):

for d in df2.columns:
if d is not 'dates':
    df2[d] = df2[d].map(lambda x: float(x)/100)

但这给了我以下警告:

 home/<xxxx>/Downloads/pycharm-community-4.5/helpers/pydev/pydevconsole.py:3: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  try:

我已经阅读了有关视图与副本的文档,但很难理解为什么它在我的情况下是一个问题,而不是在我链接的问题的代码片段中。感谢

编辑:

df2=df2.convert_objects(convert_numeric=True)

诀窍,虽然我收到折旧警告(奇怪的是,这不在http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.convert_objects.html的文档中)

一些df2:

     dates    Agric    Food     Soda     Beer     Smoke    Toys     Fun    \
dates                                                                           
192607  192607     2.37     0.12   -99.99    -5.19     1.29     8.65     2.50   
192608  192608     2.23     2.68   -99.99    27.03     6.50    16.81    -0.76   
192609  192609    -0.57     1.58   -99.99     4.02     1.26     8.33     6.42   
192610  192610    -0.46    -3.68   -99.99    -3.31     1.06    -1.40    -5.09   
192611  192611     6.75     6.26   -99.99     7.29     4.55     0.00     1.82   

Edit2:解决方案实际上比我想象的更简单:

df2.index = pd.to_datetime(df2['dates'], format = '%Y%m')
df2 = df2.astype(float)/100

3 个答案:

答案 0 :(得分:2)

我会尝试以下方法强制将所有内容转换为浮点数:

Goo<X1> a;

答案 1 :(得分:1)

您可以通过

将特定列转换为float(或任何数字类型)
df["column_name"] = pd.to_numeric(df["column_name"])

发布此内容是因为pandas 0.20.1中不推荐使用pandas.convert_objects

答案 2 :(得分:0)

您需要指定convert_objects的结果,因为没有inplace参数:

df2=df2.convert_objects(convert_numeric=True)

您引用的是rename方法,但该方法的inplace参数设置为True

pandas中的大多数操作都会返回一个副本,而有些操作会返回inplace param,而convert_objects则不会。这可能是因为如果转换失败,那么您不希望使用NaNs对您的数据进行审核。

另外,弃用警告是拆分不同的转换例程,大概是因为你可以专门化params,例如datetime等的格式字符串..

相关问题