astudentofmaths
astudentofmaths

Reputation: 1163

read_csv multi indexing dataframe

I have the following csv:

               value    value   value   value ...
id             1        1       1       2
indic          1        2       3       1
valuedate           
05/01/1970    1.0       2.0     3.2     5.2
06/01/1970    4.1       ...
07/01/1970          
08/01/1970      

that I want to read in a pandas DataFrame, so I do the following:

df=pd.read_csv("mycsv.csv", skipinitialspace=True, tupleize_cols=True)

but get the following error:

IndexError: Too many levels: Index has only 1 level, not 2

I suspect there might be an error with the multi indexing but I don't understand how to use the parameters of read_csv in order to solve this. (NB: valuedate is the name of the index column)

I want to get this data into a DataFrame that would be multi-indexed: several indic sub columns under the id column.

Upvotes: 1

Views: 539

Answers (1)

user8213249
user8213249

Reputation:

file.csv:

               value    value   value   value
id             1        1       1       2
indic          1        2       3       1
valuedate           
05/01/1970    1.0       2.0     3.2     5.2

Do:

import pandas as pd

df = pd.read_csv("file.csv", index_cols=0, delim_whitespace=True)
print(df)

Output:

            value  value.1  value.2  value.3
id            1.0      1.0      1.0      2.0
indic         1.0      2.0      3.0      1.0
valuedate     NaN      NaN      NaN      NaN
05/01/1970    1.0      2.0      3.2      5.2

Upvotes: 2

Related Questions