Search code examples
pandasgspread

How do I import rows of a Google Sheet into Pandas, but with column names?


There are great instructions in a number of places to import a Google Sheet into a Pandas DataFrame using gspread, eg:

# Open our new sheet and read some data.
worksheet = gc.open_by_key('...').sheet1

# get_all_values gives a list of rows.
rows = worksheet.get_all_values()

# Convert to a DataFrame and render.
import pandas as pd
df = pd.DataFrame.from_records(rows)
df.head()

The problem is that this import treats the first row as a value rather than as a header.

How can I import the DataFrame and treat the first row as column names instead of values?


Solution

  • You can do

    row=[[1,2,3,4]]*3
    pd.DataFrame.from_records(row[1:],columns=row[0])
       1  2  3  4
    0  1  2  3  4
    1  1  2  3  4