mHelpMe
mHelpMe

Reputation: 6668

dataframe treating my first column as an index

I am querying some data from a SQL table into a dataframe using the read_sql_query method.

It works however there is one thing I don't quite understand.

So my SQL query selects 3 columns, the first is date (all unique), the second some text and third a float.

When I run df.dtypes I get the following output,

 City         object
 Population   float64

Why has it ignore my date column? It has made it the index for the dataframe. What if I don't want this behaviour, is there anyway to stop this?

Update

Below are the paramters I pass to the function.

df = pd.read_sql_query(query, cnxn) 

When I run df.Head(3) the output is like,

               City     Population

  Date
  2018-01-01   Paris    4
  2018-01-02   NY       6
  2018-01-03   London   5

Upvotes: 0

Views: 2450

Answers (1)

ulmefors
ulmefors

Reputation: 516

You start with this where you have a DateIndex

df = pd.DataFrame({
    'City': ['Paris', 'NY', 'London'],
    'Population': [4, 6, 5],
    'Date': pd.date_range('2018-01-01', '2018-01-03')
})
df = df.set_index('Date')

>>> df
            City    Population
Date        
2018-01-01  Paris   4
2018-01-02  NY      6
2018-01-03  London  5

Fortunately, it's as simple as calling reset_index().

>>> df.reset_index()

    Date        City    Population
0   2018-01-01  Paris   4
1   2018-01-02  NY      6
2   2018-01-03  London  5

Upvotes: 1

Related Questions