Python pandas DataFrame - Convert Python list to pandas DataFrame

pandas is a Python library analyzing data. DataFrame is a basic data form in pandas.

import pandas

a = [29, 19, 40, 21]

df = pandas.DataFrame(a)

print(df)
#     0
# 0  29
# 1  19
# 2  40
# 3  21

DataFrame is a table with data, index, column name. The indexes start from 0 like Python list and in the above case the column name is 0.

Add columns

Setting columns argument, the header of dataframe has columns.

import pandas

a = [29, 19, 40, 21]

df = pandas.DataFrame(a, columns=['Population'])

print(df)
#    Population
# 0          29
# 1          19
# 2          40
# 3          21

List of tuples

import pandas

a = [
    ('Texas', 29),
    ('New York', 19),
    ('California', 40),
    ('Florida', 21),
]

df = pandas.DataFrame(a, columns=['State', 'Population'])

print(df)
#         State  Population
# 0       Texas          29
# 1    New York          19
# 2  California          40
# 3     Florida          21

If a is the list of State-Population tuples, pandas DataFrame shows the above table. Check columns argument is a list and the number of each tuple of a and columns are the same.

The first element of tuple corresponds to State, the second corresponds to Population.

Get all the rows by columns

import pandas

a = [
    ('Texas', 29),
    ('New York', 19),
    ('California', 40),
    ('Florida', 21),
]

df = pandas.DataFrame(a, columns=['State', 'Population'])

print(df)
#         State  Population
# 0       Texas          29
# 1    New York          19
# 2  California          40
# 3     Florida          21

states = df[['State']]

print(states)
#         State
# 0       Texas
# 1    New York
# 2  California
# 3     Florida

df[['State']] represents all the State rows.

Comments

Powered by Markdown

More