Link Search Menu Expand Document (external link)

How to create a data frame from scratch

Description

Sometimes it is useful to create a small table of data directly in code, without first needing to store the data in a file and load it from there. This can be useful for creating small tables for testing purposes, or for creating small lookup tables that hold abbreviations, IDs, etc. What’s the easiest way to build such a table?

Solution, in Python

View this solution alone.

In pandas, the pd.DataFrame function can construct new DataFrames. Just provide it with a dictionary whose keys are the column headers and whose values are the column contents.

Here’s an example:

1
2
3
4
5
6
7
import pandas as pd
df = pd.DataFrame( {
    'Last name' :  [ 'Potter', 'Weasley', 'Granger', 'Malfoy' ],
    'First name' : [ 'Harry', 'Ron', 'Hermione', 'Draco' ],
    'House' :      [ 'Gryffindor', 'Gryffindor', 'Gryffindor', 'Slytherin' ]
} )
df
Last name First name House
0 Potter Harry Gryffindor
1 Weasley Ron Gryffindor
2 Granger Hermione Gryffindor
3 Malfoy Draco Slytherin

Content last modified on 24 July 2023.

See a problem? Tell us or edit the source.

Solution, in R

View this solution alone.

In R, the data.frame function can be used to build data frames. Each column in your data should be a separate parameter, with its name provided, followed by an equals sign, followed by the vector of column contents, as shown in the example below.

1
2
3
4
5
6
data <- data.frame(
    last.name =  c( 'Potter', 'Weasley', 'Granger', 'Malfoy' ),
    first.name = c( 'Harry', 'Ron', 'Hermione', 'Draco' ),
    house =      c( 'Griffindor', 'Griffindor', 'Griffindor', 'Slytherin' )
)
data
1
2
3
4
5
  last.name first.name house     
1 Potter    Harry      Griffindor
2 Weasley   Ron        Griffindor
3 Granger   Hermione   Griffindor
4 Malfoy    Draco      Slytherin 

Content last modified on 24 July 2023.

See a problem? Tell us or edit the source.

Topics that include this task

Opportunities

This website does not yet contain a solution for this task in any of the following software packages.

  • Excel
  • Julia

If you can contribute a solution using any of these pieces of software, see our Contributing page for how to help extend this website.