initialize dataframe in python

To initialize a dataframe in Python using pandas, you can use one of several methods:

  1. Creating an empty dataframe:
main.py
import pandas as pd
df = pd.DataFrame()
40 chars
3 lines
  1. Creating a dataframe from a dictionary:
main.py
import pandas as pd
data = {'name': ['John', 'Mike', 'Sarah'], 'age': [25, 23, 30]}
df = pd.DataFrame(data)
108 chars
4 lines
  1. Creating a dataframe from a list of lists:
main.py
import pandas as pd
data = [['John', 25], ['Mike', 23], ['Sarah', 30]]
df = pd.DataFrame(data, columns=['name', 'age'])
120 chars
4 lines
  1. Creating a dataframe from a NumPy array:
main.py
import pandas as pd
import numpy as np
data = np.array([['John', 25], ['Mike', 23], ['Sarah', 30]])
df = pd.DataFrame(data, columns=['name', 'age'])
149 chars
5 lines

There are also other methods for initializing dataframes using pandas, but these are the most common ones.

gistlibby LogSnag