skolukmar
skolukmar

Reputation: 331

How to create data frame with duplicated column name

I need to create a data frame with the same name. Using the standard approach:

df=pd.DataFrame(data={
    'colName': [1],
    'colName': [2]
   })

i get

   colName
0        2

instead of

   colName colName
0        1       2

Do you have any idea how to create excepted data frame? It is required fot Unit Tests.

Upvotes: 0

Views: 231

Answers (2)

Quang Hoang
Quang Hoang

Reputation: 150735

Python dictionary automatically overrides duplicate keys. So

{
'colName': [1],
'colName': [2]
}

is actually just one key. One way to go is:

# row wise 
df = pd.DataFrame([[1,2],[3,4],[5,6]])
# or column wise
# df = pd.DataFrame({0:[1,3,5], 1:[2,4,6]})

df.columns = ['colName', 'colName']

However, I should not that duplicate column names are discourage in Pandas.

Upvotes: 2

Mayank Porwal
Mayank Porwal

Reputation: 34046

One way could be:

In [452]: df=pd.DataFrame(data={
     ...:     'colName1': [1],
     ...:     'colName2': [2]
     ...:    })

In [453]: df
Out[453]: 
   colName1  colName2
0         1         2

In [454]: df.columns = ['colName', 'colName']

In [455]: df
Out[455]: 
   colName  colName
0        1        2

Upvotes: 2

Related Questions