emmby
emmby

Reputation: 100464

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?

Upvotes: 2

Views: 2977

Answers (2)

Alicia
Alicia

Reputation: 151

I had the same issue - instead of getting a list of lists via get_all_values(), I changed it to get_all_records() and the column headers populated just fine.

for sheet in sheet_names:
   worksheet = sh.worksheet(sheet)
   rows = pd.DataFrame(worksheet.get_all_records())
   database = pd.concat([database, rows])

Upvotes: 2

BENY
BENY

Reputation: 323276

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

Upvotes: 4

Related Questions