Pandas 数据框将特定列从字符串转换为浮点数

zun*_*rtj 5 python pandas

我正在尝试对 Kenneth French 行业投资组合进行一些简单的分析(第一次使用 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
Run Code Online (Sandbox Code Playgroud)

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

df2.convert_objects(convert_numeric=True)
Run Code Online (Sandbox Code Playgroud)

但列仍然是字符串。其他建议是循环遍历列(例如,请参阅pandas 将字符串转换为 dataframe 中多列的浮动):

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

但这给了我以下警告:

 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:
Run Code Online (Sandbox Code Playgroud)

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

编辑:

df2=df2.convert_objects(convert_numeric=True)
Run Code Online (Sandbox Code Playgroud)

尽管我收到了折旧警告,但确实有效(奇怪的是,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   
Run Code Online (Sandbox Code Playgroud)

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

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

EdC*_*ica 0

您需要分配结果,convert_objects因为没有inplace参数:

df2=df2.convert_objects(convert_numeric=True)
Run Code Online (Sandbox Code Playgroud)

您引用了该rename方法,但该方法有一个inplace您设置为的参数True

pandas 中的大多数操作都会返回一个副本,有些有inplace参数,convert_objects有些则没有。这可能是因为如果转换失败,那么您不想用NaNs.

另外,弃用警告是为了拆分不同的转换例程,大概这样您就可以专门化参数,例如日期时间的格式字符串等。