Skip to content

Dataframes

To correlate our various measurements, we want some table-like data structure, so we import Dataframes:

from pandas import DataFrame  # Note the camel-case spelling

Crating Dataframes

A dataframe can be created from a list of series, where each series forms a row in the resulting table.

measurements = DataFrame(data=[sneeze_counts, temperatures, humidities])
print(measurements)
Output
             Monday  Tuesday  Wednesday  Thursday  Friday  Saturday  Sunday
Sneezes        32.0     41.0       56.0      62.0    30.0      22.0    17.0
Temperature    10.9      8.2        7.6       7.8     9.4      11.1    12.4
Humidity       62.5     76.3       82.4      98.2    77.4      58.9    41.2

A dataframe can also be created from a dictionary of series where each series forms a column in the resulting table.

measurements = DataFrame(
  data={
    sneeze_counts.name: sneeze_counts,
    temperatures.name: temperatures,
    humidities.name: humidities
  }
)
print(measurements)
Output
           Sneezes  Temperature  Humidity
Monday          32         10.9      62.5
Tuesday         41          8.2      76.3
Wednesday       56          7.6      82.4
Thursday        62          7.8      98.2
Friday          30          9.4      77.4
Saturday        22         11.1      58.9
Sunday          17         12.4      41.2

Turn around

To flip rows and columns, dataframes can be transposed using the T-property:

column_wise = DataFrame(data=temperatures)
row_wise = column_wise.T

print(column_wise)
print()  # Add a blank line as separator
print(row_wise)
Output
           Temperature
Monday            10.9
Tuesday            8.2
Wednesday          7.6
Thursday           7.8
Friday             9.4
Saturday          11.1
Sunday            12.4

             Monday  Tuesday  Wednesday  Thursday  Friday  Saturday  Sunday
Temperature    10.9      8.2        7.6       7.8     9.4      11.1    12.4

Don’t forget to store the transposed dataframe in a new variable (or overwrite the old one), as the original will not be changed by the transposition.

Key Points

  • Dataframes represent 2-dimensional (tabular) data
  • Each column in a dataframe is a series
  • Dataframes have row and column indices
  • Dataframes may be transposed to switch rows and columns