1

When I tried to read the data from a csv file. I want to set the 'Data' column's datatype as float, so my code is like:

data = pd.read_csv('data.csv', index_col=0, 
                   parse_dates=[0], 
                   skiprows=[0], names=['Data'],
                   dtype={'Data':np.float32})

But the result I got is still list of strings. Is there any reason and any solution for it?

[5]: data.values

[5]: array([['1188.0'],
            ['1377.0'],
            ['1279.0'],
            ['1461.0'],
            ['1146.0'],
            ['1287.0'],
            ['1259.0']], dtype=object)

1 Answer 1

1

Add value to names parameter:

import pandas as pd
import numpy as np
from io import StringIO

temp="""2019-01-02,1188.0
2019-01-03,1377.0
2019-01-04,1279.0
2019-01-05,1461.0
2019-01-06,1146.0
2019-01-07,1287.0
2019-01-08,1259.0"""
#after testing replace 'pd.compat.StringIO(temp)' to 'data.csv'
df = pd.read_csv(StringIO(temp),
                 index_col=0,
                 parse_dates=[0],
                 names=['dates','Data'],
                 dtype={'Data':np.float32})

print (df)
              Data
dates             
2019-01-02  1188.0
2019-01-03  1377.0
2019-01-04  1279.0
2019-01-05  1461.0
2019-01-06  1146.0
2019-01-07  1287.0
2019-01-08  1259.0

print (df.dtypes)
Data    float32
dtype: object

print (df.index)
DatetimeIndex(['2019-01-02', '2019-01-03', '2019-01-04', '2019-01-05',
               '2019-01-06', '2019-01-07', '2019-01-08'],
              dtype='datetime64[ns]', name='dates', freq=None)
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your answer, but actually the csv file includes 2 columns: date and data. If I remove the parse_date, I can have the correct datatype. So does it means that I couldn't achieve both in one line? Does the parse_date function conflicts with the datatype specification? Thanks!
@Kid - So I think you need df = pd.read_csv('data.csv', index_col=0, names=['Data'], dtype={'Data':np.float32})
@Kid - Solution was changed completely.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.