CedM
CedM

Reputation: 91

How to merge header informations?

After a read_csv file, I've a DataFrame where header is in the header and line 0, like this :

   Unnamed: 0 Unnamed: 1  Temp    Hi   Low  Out  Dew   Wind Wind.1 Wind.2   Hi.1  ...   In    In In .1 In .2 In .3   In Air Unnamed: 30 Wind.4 Wind.5    ISS   Arc.

   0        Date       Time   Out  Temp  Temp  Hum  Pt.  Speed    Dir    Run  Speed  ...  Temp  Hum   Dew  Heat   EMC  Density         ET    Samp    Tx   Recept  Int.

   1    09/04/19      11:05   ---   ---   ---  ---  ---    0.0    ---   0.00    0.0  ...  27.8   30   8.6  26.6  6.05   1.1483        0.00      0      1     0.0     5

   2    09/04/19      11:10   ---   ---   ---  ---  ---    0.0    ---   0.00    0.0  ...  28.1   29   8.4  26.8  5.85   1.1475        0.00      0      1     0.0     5

   3    09/04/19      11:15   ---   ---   ---  ---  ---    0.0    ---   0.00    0.0  ...  28.2   29   8.5  27.0  5.85   1.1468        0.00      0      1     0.0     5

I would like to merge the actual header with the line 0 and set a space in between for example (and datas are after from line 1 to the end). How to do so ? Regards.

Upvotes: 1

Views: 74

Answers (2)

Quang Hoang
Quang Hoang

Reputation: 150745

I would read the file without headers, transpose, and join:

df = pd.read_csv('filename.csv', header=None).T

df['new index'] = df[0].fillna('').str + ' ' + df[1].str

df.set_index('new index', inplace=True)
df.drop([0,1], inplace=True, axis=1)

df = df.T

Upvotes: 0

BENY
BENY

Reputation: 323246

When you read the csv files you can point header is first two line , then you will have multiple index on columns

df = pd.read_csv('test.csv', header=[0, 1])
df.columns=df.columns.map(' '.join)

Upvotes: 2

Related Questions