1

I have a data as shown below,

x = [1,2,3,4,5]
y = [6,7,8,9,0]
z = [11,12,12,56,6]

Now, I want to export this data to an excel file. For that I have used the following code

import numpy as np
import pandas as pd

data = pd.DataFrame({"x":[1,2,3,4,5],
                     " ":np.nan,
                     "y":[6,7,8,9,0],
                     " ":np.nan,
                     "z":[11,12,12,56,6]})
data.to_excel('test_file.xlsx', index= False)

Here I used the np.nan to create an empty column.

The new excel file is as shown

enter image description here

but, I want to show the data as shown in this picture enter image description here

Please help. Thank you.

2 Answers 2

1

There is problem your dictionary of lists contain duplicate column name ' ' and it is per design not allowed. So is possible create DataFrame by column_stack and define columns names:

empty =  [np.nan] * len(x)
data = pd.DataFrame(np.column_stack([x,empty,z,empty,y]), columns= ['x','','y','','z'])

Or a little hack - create all unique columns first in dict and then rename:

data = pd.DataFrame({"x":x,
                     "empty1":np.nan,
                     "y":y,
                     "empty2":np.nan,
                     "z":z}, columns=['x','empty1','y','empty2','z'])
data = data.rename(columns={'empty1':'', 'empty2':''})         

print (data)
     x         y        z
0  1.0 NaN  11.0 NaN  6.0
1  2.0 NaN  12.0 NaN  7.0
2  3.0 NaN  12.0 NaN  8.0
3  4.0 NaN  56.0 NaN  9.0
4  5.0 NaN   6.0 NaN  0.0


data.to_excel('test_file.xlsx', index= False)
Sign up to request clarification or add additional context in comments.

Comments

0

you can try this way also ( no cost hack :) )

data = pd.DataFrame({"x": [1,2,3,4,5],
                     "": np.nan,
                     "y": [6,7,8,9,0],
                     None: np.nan,
                     "z": [11,12,12,56,6]})

Comments

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.