Pobieranie danych z wielu arkuszy

Sprawne importowanie danych z pandas

Amany Mahfouz

Instructor

Wybór arkuszy do załadowania

  • read_excel() domyślnie ładuje pierwszy arkusz pliku Excel
  • Argument sheet_name pozwala załadować inne arkusze
  • Arkusze można wskazać nazwą lub numerem pozycji (indeksowanie od zera)
  • Lista nazw/numerów umożliwia załadowanie wielu arkuszy jednocześnie
  • Wszystkie argumenty read_excel() dotyczą każdego ładowanego arkusza
Sprawne importowanie danych z pandas

Wybór arkuszy do załadowania

Zrzut ekranu programu arkuszowego z widocznymi zakładkami dwóch arkuszy

Sprawne importowanie danych z pandas

Ładowanie wybranych arkuszy

# Get the second sheet by position index
survey_data_sheet2 = pd.read_excel('fcc_survey.xlsx',
                                   sheet_name=1)

# Get the second sheet by name survey_data_2017 = pd.read_excel('fcc_survey.xlsx', sheet_name='2017')
print(survey_data_sheet2.equals(survey_data_2017))
True
Sprawne importowanie danych z pandas

Ładowanie wszystkich arkuszy

  • Przekazanie sheet_name=None do read_excel() wczytuje wszystkie arkusze ze skoroszytu
survey_responses = pd.read_excel("fcc_survey.xlsx", sheet_name=None)

print(type(survey_responses))
<class 'collections.OrderedDict'>
for key, value in survey_responses.items():
    print(key, type(value))
2016 <class 'pandas.core.frame.DataFrame'>
2017 <class 'pandas.core.frame.DataFrame'>
Sprawne importowanie danych z pandas

Łączenie danych

# Create empty dataframe to hold all loaded sheets
all_responses = pd.DataFrame()

# Iterate through dataframes in dictionary for sheet_name, frame in survey_responses.items(): # Add a column so we know which year data is from frame["Year"] = sheet_name
# Add the dataframe to all_responses all_responses = pd.concat([all_responses, frame])
# View years in data print(all_responses.Year.unique())
['2016' '2017']
Sprawne importowanie danych z pandas

Czas na ćwiczenia!

Sprawne importowanie danych z pandas

Preparing Video For Download...