ZetCode

Python pandas

last modified November 18, 2026 Python 3.15

In this article we show how to do basic data analysis in Python with the pandas library.

Pandas

pandas is an open source, BSD-licensed library providing fast, easy-to-use data structures and data analysis tools for Python. The name comes from panel data, an econometrics term for data sets with observations over multiple time periods for the same individuals.

The two main data types are Series and DataFrame. A Series is a one-dimensional labeled array of values of a single type. A DataFrame is a two-dimensional, size-mutable table with labeled rows and columns, similar to a spreadsheet or an SQL table. Each column of a DataFrame is a Series. The row labels form the index.

The examples use pandas 3, which changed several defaults: text columns have a dedicated string dtype, and Copy-on-Write rules decide when data is shared between objects. Both are covered below.

Installation

pandas is an external library; we install it with pip install pandas. It depends on NumPy. The optional PyArrow package speeds up string columns and adds support for more file formats.

version.py
import pandas as pd

print(pd.__version__)

We print the version of the library.

$ python version.py
3.1.1

Simple example

The following example creates a small DataFrame.

simple.py
import pandas as pd

data = [['Alex', 10], ['Ronald', 18], ['Jane', 33]]
df = pd.DataFrame(data, columns=['Name', 'Age'])

print(df)
print(df.dtypes)

We create a DataFrame from a list of rows and give the columns names. pandas adds a default index of integers starting from 0.

print(df.dtypes)

The dtypes attribute shows the type of each column. Since pandas 3, text columns have the str dtype. Older versions stored them as the generic object dtype, which could hold any Python object.

$ python simple.py
     Name  Age
0    Alex   10
1  Ronald   18
2    Jane   33
Name      str
Age     int64
dtype: object

DataFrame from a dictionary

More often, we create a DataFrame from a dictionary of columns.

from_dict.py
import pandas as pd

data = {'name': ['Alex', 'Ronald', 'Jane'],
        'age': [10, 18, 33],
        'city': ['Bratislava', 'Brno', 'Vienna']}

df = pd.DataFrame(data, index=['a', 'b', 'c'])
print(df)

print(df.index)
print(df.columns)
print(df.shape)
print(df.to_numpy())

The dictionary keys become the column names. We also pass a custom index.

print(df.index)
print(df.columns)
print(df.shape)
print(df.to_numpy())

The index and columns attributes hold the row and column labels, and shape the number of rows and columns. The to_numpy method returns the data as a NumPy array; for mixed types, the array has the object type.

$ python from_dict.py
     name  age        city
a    Alex   10  Bratislava
b  Ronald   18        Brno
c    Jane   33      Vienna
Index(['a', 'b', 'c'], dtype='str')
Index(['name', 'age', 'city'], dtype='str')
(3, 3)
[['Alex' 10 'Bratislava']
 ['Ronald' 18 'Brno']
 ['Jane' 33 'Vienna']]

Creating a Series

A Series can be created from a list, a dictionary, a NumPy array, or a scalar value.

series_create.py
import numpy as np
import pandas as pd

s1 = pd.Series([4, 7, 2, 9])
print(s1)

s2 = pd.Series([4, 7, 2, 9], index=['a', 'b', 'c', 'd'], name='vals')
print(s2)

s3 = pd.Series({'coins': 22, 'pens': 3, 'books': 28})
print(s3)

s4 = pd.Series(np.linspace(0, 1, 3))
print(s4)

s5 = pd.Series(5, index=['x', 'y', 'z'])
print(s5)

Without an index, pandas numbers the values from 0. From a dictionary, the keys become the index. A scalar value is repeated for every label of the index. The name becomes the column name when the series is put into a DataFrame.

$ python series_create.py
0    4
1    7
2    2
3    9
dtype: int64
a    4
b    7
c    2
d    9
Name: vals, dtype: int64
coins    22
pens      3
books    28
dtype: int64
0    0.0
1    0.5
2    1.0
dtype: float64
x    5
y    5
z    5
dtype: int64

Accessing Series values

Values are accessed by label with loc or square brackets, and by position with iloc.

series_access.py
import pandas as pd

s = pd.Series({'coins': 22, 'pens': 3, 'books': 28})

print(s['pens'])
print(s.loc['coins'])
print(s.iloc[0])
print(s.iloc[-1])

print(s[['coins', 'books']])

try:
    s[0]
except KeyError as e:
    print(f'KeyError: {e}')

We get values by label and by position, and select several values with a list of labels.

try:
    s[0]
except KeyError as e:
    print(f'KeyError: {e}')

Square brackets always use labels in pandas 3. With a string index, s[0] raises a KeyError; older versions fell back to the position with a deprecation warning. We use iloc for positions.

$ python series_access.py
3
22
22
28
coins    22
books    28
dtype: int64
KeyError: 0

Series operations

Operations on a Series are applied to all values at once, and operations between two series align the values by their labels.

series_ops.py
import pandas as pd

prices = pd.Series({'apples': 1.2, 'pears': 2.5, 'plums': 3.1})
qty = pd.Series({'pears': 4, 'apples': 10, 'kiwis': 3})

print(prices * 2)
print(prices[prices > 2])

total = prices * qty
print(total)
print(total.sum())

print(prices.mean(), prices.max(), prices.idxmax())

We double all prices and filter them with a boolean condition.

total = prices * qty

The multiplication pairs apples with apples and pears with pears, regardless of the order. Labels found in only one of the series produce NaN, which the sum method skips. The idxmax method returns the label of the largest value.

$ python series_ops.py
apples    2.4
pears     5.0
plums     6.2
dtype: float64
pears    2.5
plums    3.1
dtype: float64
apples    12.0
kiwis      NaN
pears     10.0
plums      NaN
dtype: float64
22.0
2.266666666666667 3.1 plums

Reading CSV

The read_csv function reads a CSV file into a DataFrame. We use a small file with fictional employee data.

employees.csv
id,name,department,city,salary,hired
1,Jane Doe,Sales,Bratislava,2450,2019-03-14
2,John Smith,IT,Brno,3900,2017-08-01
3,Lucy Brown,IT,Bratislava,4200,2015-01-20
4,Peter Novak,Marketing,Vienna,3100,2021-06-07
5,Anna Kovac,Sales,Brno,2300,2022-11-02
6,Robert Black,IT,Vienna,5100,2012-04-16
7,Maria Horvath,HR,Bratislava,2800,2018-09-24
8,Tomas Kral,Sales,Vienna,,2024-02-12
9,Eva Varga,Marketing,Bratislava,3350,2020-05-18
10,Paul Green,IT,Brno,4600,2016-10-03
11,Sofia Ruiz,HR,Vienna,2950,2023-01-09
12,Martin Bielik,Sales,Bratislava,2600,2020-07-27

The file has a header row and twelve records; one salary is missing.

read_csv.py
import pandas as pd

df = pd.read_csv('employees.csv', parse_dates=['hired'])

print(df.head())
print()
print(df.tail(3))

The parse_dates option converts the hired column to dates. The head method returns the first five rows by default, the tail method the last rows. The missing salary turns the column into floats, because NaN is a float value.

$ python read_csv.py
   id         name department        city  salary      hired
0   1     Jane Doe      Sales  Bratislava  2450.0 2019-03-14
1   2   John Smith         IT        Brno  3900.0 2017-08-01
2   3   Lucy Brown         IT  Bratislava  4200.0 2015-01-20
3   4  Peter Novak  Marketing      Vienna  3100.0 2021-06-07
4   5   Anna Kovac      Sales        Brno  2300.0 2022-11-02

    id           name department        city  salary      hired
9   10     Paul Green         IT        Brno  4600.0 2016-10-03
10  11     Sofia Ruiz         HR      Vienna  2950.0 2023-01-09
11  12  Martin Bielik      Sales  Bratislava  2600.0 2020-07-27

DataFrame info

The info method prints a concise summary of a DataFrame.

info.py
import pandas as pd

df = pd.read_csv('employees.csv', parse_dates=['hired'])

df.info()

We see the number of rows, the columns with their non-null counts and types, and the memory usage. Dates are stored with microsecond resolution; pandas 3 no longer converts everything to nanoseconds.

$ python info.py
<class 'pandas.DataFrame'>
RangeIndex: 12 entries, 0 to 11
Data columns (total 6 columns):
 #   Column      Non-Null Count  Dtype         
---  ------      --------------  -----         
 0   id          12 non-null     int64         
 1   name        12 non-null     str           
 2   department  12 non-null     str           
 3   city        12 non-null     str           
 4   salary      11 non-null     float64       
 5   hired       12 non-null     datetime64[us]
dtypes: datetime64[us](1), float64(1), int64(1), str(3)
memory usage: 708.0 bytes

Describing data

The describe method computes summary statistics.

describe.py
import pandas as pd

df = pd.read_csv('employees.csv', parse_dates=['hired'])

print(df['salary'].describe())
print()
print(df.describe(include='str'))

For a numeric column, we get the count, mean, standard deviation, minimum, quartiles, and maximum. The count is 11, because the missing value is excluded. For string columns, selected with include='str', we get the number of unique values, the most frequent value, and its frequency.

$ python describe.py
count      11.000000
mean     3395.454545
std       928.831133
min      2300.000000
25%      2700.000000
50%      3100.000000
75%      4050.000000
max      5100.000000
Name: salary, dtype: float64

            name department        city
count         12         12          12
unique        12          4           3
top     Jane Doe      Sales  Bratislava
freq           1          4           5

Counting values

The value_counts method counts the occurrences of each value.

counting.py
import pandas as pd

df = pd.read_csv('employees.csv')

print(df['city'].value_counts())
print()
print(df['department'].value_counts(normalize=True).round(2))
print()
print(df['department'].nunique(), df['department'].unique().tolist())

We count employees by city. With normalize=True, we get proportions instead of counts. The nunique and unique methods return the number of distinct values and the values themselves.

$ python counting.py
city
Bratislava    5
Vienna        4
Brno          3
Name: count, dtype: int64

department
Sales        0.33
IT           0.33
Marketing    0.17
HR           0.17
Name: proportion, dtype: float64

4 ['Sales', 'IT', 'Marketing', 'HR']

Selecting columns

Square brackets with a column name return a Series; with a list of names, they return a DataFrame.

select_columns.py
import pandas as pd

df = pd.read_csv('employees.csv')

names = df['name']
print(type(names))
print(names.head(3))

print(df[['name', 'salary']].head(3))

We select a single column and then two columns.

$ python select_columns.py
<class 'pandas.Series'>
0      Jane Doe
1    John Smith
2    Lucy Brown
Name: name, dtype: str
         name  salary
0    Jane Doe  2450.0
1  John Smith  3900.0
2  Lucy Brown  4200.0

Selecting with loc

The loc indexer selects rows and columns by labels or by a boolean condition.

select_loc.py
import pandas as pd

df = pd.read_csv('employees.csv', index_col='id')

print(df.loc[3])
print()
print(df.loc[2:4, ['name', 'city']])
print()
print(df.loc[df['city'] == 'Vienna', 'name'])

We use the id column as the index. df.loc[3] returns the row with the label 3 as a series. A slice of labels includes both ends, unlike Python slices. The last selection combines a condition for the rows with a column label.

$ python select_loc.py
name          Lucy Brown
department            IT
city          Bratislava
salary            4200.0
hired         2015-01-20
Name: 3, dtype: object

           name        city
id                         
2    John Smith        Brno
3    Lucy Brown  Bratislava
4   Peter Novak      Vienna

id
4      Peter Novak
6     Robert Black
8       Tomas Kral
11      Sofia Ruiz
Name: name, dtype: str

Selecting with iloc

The iloc indexer selects rows and columns by integer position.

select_iloc.py
import pandas as pd

df = pd.read_csv('employees.csv')

print(df.iloc[0, 1])
print(df.iloc[:3, 1:4])
print(df.iloc[[0, -1], [1, 4]])

We get a single value, the first three rows of three columns, and the first and last rows of two columns. Position slices exclude the end, as in plain Python.

$ python select_iloc.py
Jane Doe
         name department        city
0    Jane Doe      Sales  Bratislava
1  John Smith         IT        Brno
2  Lucy Brown         IT  Bratislava
             name  salary
0        Jane Doe  2450.0
11  Martin Bielik  2600.0

Filtering rows

Rows are filtered with boolean conditions. Several conditions are combined with the &, |, and ~ operators; each condition must be in parentheses.

filtering.py
import pandas as pd

df = pd.read_csv('employees.csv')

print(df[(df['salary'] > 3000) & (df['salary'] < 4500)][['name', 'salary']])
print()
print(df[df['city'].isin(['Brno', 'Vienna']) & (df['department'] == 'IT')][['name', 'city']])
print()
print(df.query('department == "Sales" and salary >= 2450')[['name', 'salary']])

We select employees with salaries in a range, and IT employees from two cities using isin.

print(df.query('department == "Sales" and salary >= 2450')[['name', 'salary']])

The query method takes the condition as a string, which is often easier to read. The and and or keywords work inside the query. Comparisons with NaN are false, so the employee without a salary is not included.

$ python filtering.py
          name  salary
1   John Smith  3900.0
2   Lucy Brown  4200.0
3  Peter Novak  3100.0
8    Eva Varga  3350.0

           name    city
1    John Smith    Brno
5  Robert Black  Vienna
9    Paul Green    Brno

             name  salary
0        Jane Doe  2450.0
11  Martin Bielik  2600.0

String methods

The str accessor applies string methods to every value of a string column.

string_methods.py
import pandas as pd

df = pd.read_csv('employees.csv')

print(df['name'].dtype)

last = df['name'].str.split().str[1]
print(last.str.upper().head(3).tolist())

print(df.loc[df['name'].str.startswith(('M', 'P')), 'name'].tolist())
print(df['city'].str.len().max())

We split the names into words, take the last names, and convert them to uppercase. The startswith method accepts a tuple of prefixes and returns a boolean series for filtering.

$ python string_methods.py
str
['DOE', 'SMITH', 'BROWN']
['Peter Novak', 'Maria Horvath', 'Paul Green', 'Martin Bielik']
10

Adding columns

New columns are created by assignment or with the assign method.

new_columns.py
import pandas as pd

df = pd.read_csv('employees.csv', parse_dates=['hired'])

df['yearly'] = df['salary'] * 12
df = df.assign(years=2026 - df['hired'].dt.year,
               senior=lambda d: d['years'] >= 8)

print(df[['name', 'salary', 'yearly', 'years', 'senior']].head(6))

The yearly column is computed from the salary for all rows at once.

df = df.assign(years=2026 - df['hired'].dt.year,
               senior=lambda d: d['years'] >= 8)

The assign method returns a new DataFrame. The dt accessor gives access to the parts of dates. A lambda receives the DataFrame being built, so the senior column can use the years column created in the same call.

$ python new_columns.py
           name  salary   yearly  years  senior
0      Jane Doe  2450.0  29400.0      7   False
1    John Smith  3900.0  46800.0      9    True
2    Lucy Brown  4200.0  50400.0     11    True
3   Peter Novak  3100.0  37200.0      5   False
4    Anna Kovac  2300.0  27600.0      4   False
5  Robert Black  5100.0  61200.0     14    True

Copy-on-Write

In pandas 3, every indexing operation behaves as if it returned a copy; data is physically copied only when one of the objects is modified. This is called Copy-on-Write. It makes the behaviour predictable, but code that relied on modifying a DataFrame through another object no longer works.

copy_on_write.py
import pandas as pd

df = pd.DataFrame({'name': ['Jane', 'John', 'Lucy'], 'salary': [2450, 3900, 4200]})

df['salary'][0] = 9999
print(df)

df.loc[0, 'salary'] = 2500
print(df)

high = df[df['salary'] > 3000]
high.loc[1, 'salary'] = 0
print(df['salary'].tolist(), high['salary'].tolist())

The chained assignment df['salary'][0] = 9999 first selects the column and then modifies the selected series, which is a separate object. The DataFrame is not changed, and pandas emits a ChainedAssignmentError warning. Setting the value in one step with loc works.

high = df[df['salary'] > 3000]
high.loc[1, 'salary'] = 0

A filtered DataFrame is independent of the original: modifying it never changes df. Older versions emitted the SettingWithCopyWarning here, and the outcome depended on whether pandas had made a copy or a view.

$ python copy_on_write.py
/home/user/python/copy_on_write.py:5: ChainedAssignmentError: A value is being set on a copy of a DataFrame or Series through chained assignment.
Such chained assignment never works to update the original DataFrame or Series, because the intermediate object on which we are setting values always behaves as a copy (due to Copy-on-Write).

Try using '.loc[row_indexer, col_indexer] = value' instead, to perform the assignment in a single step.

See the documentation for a more detailed explanation: https://pandas.pydata.org/docs/dev/user_guide/migration.html#chained-assignment
  df['salary'][0] = 9999
   name  salary
0  Jane    2450
1  John    3900
2  Lucy    4200
   name  salary
0  Jane    2500
1  John    3900
2  Lucy    4200
[2500, 3900, 4200] [0, 4200]

Missing values

Missing values are represented by NaN. pandas has methods to detect, fill, and drop them.

missing.py
import pandas as pd

df = pd.read_csv('employees.csv')

print(df['salary'].isna().sum())
print(df[df['salary'].isna()][['name', 'salary']])

print(df['salary'].mean())

filled = df['salary'].fillna(df.groupby('department')['salary'].transform('median'))
print(filled.iloc[7])

print(len(df.dropna()))

The isna method returns a boolean mask; its sum is the number of missing values. Statistics such as mean skip missing values.

filled = df['salary'].fillna(df.groupby('department')['salary'].transform('median'))

We fill the missing salary with the median salary of the employee's department. The transform method returns a series of the same length as the original, with the group median on every row. The dropna method removes the rows with missing values.

$ python missing.py
1
         name  salary
7  Tomas Kral     NaN
3395.4545454545455
2450.0
11

Sorting

The sort_values method sorts the rows by one or more columns.

sorting.py
import pandas as pd

df = pd.read_csv('employees.csv')

print(df.sort_values('salary', ascending=False)[['name', 'salary']].head(4))
print()
print(df.sort_values(['department', 'salary'], ascending=[True, False])
        [['department', 'name', 'salary']].to_string(index=False))
print()
print(df.nsmallest(3, 'salary')[['name', 'salary']])

We list the four best-paid employees, and then sort by department in ascending and by salary in descending order. Missing values are placed at the end. The nsmallest and nlargest methods are a shortcut for the top or bottom rows. The to_string method with index=False prints the table without the index.

$ python sorting.py
           name  salary
5  Robert Black  5100.0
9    Paul Green  4600.0
2    Lucy Brown  4200.0
1    John Smith  3900.0

department          name  salary
        HR    Sofia Ruiz  2950.0
        HR Maria Horvath  2800.0
        IT  Robert Black  5100.0
        IT    Paul Green  4600.0
        IT    Lucy Brown  4200.0
        IT    John Smith  3900.0
 Marketing     Eva Varga  3350.0
 Marketing   Peter Novak  3100.0
     Sales Martin Bielik  2600.0
     Sales      Jane Doe  2450.0
     Sales    Anna Kovac  2300.0
     Sales    Tomas Kral     NaN

             name  salary
4      Anna Kovac  2300.0
0        Jane Doe  2450.0
11  Martin Bielik  2600.0

Grouping

The groupby method splits the data into groups, applies a function to each group, and combines the results.

groupby.py
import pandas as pd

df = pd.read_csv('employees.csv')

print(df.groupby('department')['salary'].mean().round(1))
print()

summary = df.groupby('department').agg(
    people=('name', 'count'),
    avg_salary=('salary', 'mean'),
    max_salary=('salary', 'max'),
).sort_values('avg_salary', ascending=False)

print(summary.round(1))

We compute the average salary per department. With agg and named aggregations, we compute several statistics at once and name the resulting columns. The count function counts non-missing values.

$ python groupby.py
department
HR           2875.0
IT           4450.0
Marketing    3225.0
Sales        2450.0
Name: salary, dtype: float64

            people  avg_salary  max_salary
department                                
IT               4      4450.0      5100.0
Marketing        2      3225.0      3350.0
HR               2      2875.0      2950.0
Sales            4      2450.0      2600.0

Pivot tables

A pivot table summarizes data in a two-dimensional table, like the pivot tables of spreadsheet programs.

pivot.py
import pandas as pd

df = pd.read_csv('employees.csv')

table = df.pivot_table(index='department', columns='city', values='salary',
                       aggfunc='mean', margins=True)
print(table.round(0))

We compute average salaries by department and city. Combinations without data are NaN. The margins=True option adds the All row and column with totals over all data.

$ python pivot.py
city        Bratislava    Brno  Vienna     All
department                                    
HR              2800.0     NaN  2950.0  2875.0
IT              4200.0  4250.0  5100.0  4450.0
Marketing       3350.0     NaN  3100.0  3225.0
Sales           2525.0  2300.0     NaN  2450.0
All             3080.0  3600.0  3717.0  3395.0

Working with dates

Date columns support comparisons with date strings and the dt accessor.

dates.py
import pandas as pd

df = pd.read_csv('employees.csv', parse_dates=['hired'])

print(df['hired'].dtype)
print(df['hired'].min(), df['hired'].max())

print(df.groupby(df['hired'].dt.year)['name'].count().tail(5))

recent = df[df['hired'] >= '2022-01-01']
print(recent[['name', 'hired']])

We find the earliest and latest hiring dates, count hires per year, and select employees hired since 2022. The string '2022-01-01' is converted to a date for the comparison.

$ python dates.py
datetime64[us]
2012-04-16 00:00:00 2024-02-12 00:00:00
hired
2020    2
2021    1
2022    1
2023    1
2024    1
Name: name, dtype: int64
          name      hired
4   Anna Kovac 2022-11-02
7   Tomas Kral 2024-02-12
10  Sofia Ruiz 2023-01-09

Dropping and renaming

The drop method removes rows or columns, and the rename method renames them. Both return a new DataFrame.

drop_rename.py
import pandas as pd

df = pd.read_csv('employees.csv')

df2 = df.drop(columns=['id', 'hired']).rename(columns={'salary': 'pay'})
print(df2.head(3))

df3 = df.drop(index=[0, 1])
print(df3.index[:3].tolist(), len(df), len(df3))

We drop two columns and rename the salary column. Then we drop the first two rows by their index labels; the original DataFrame keeps all twelve rows.

$ python drop_rename.py
         name department        city     pay
0    Jane Doe      Sales  Bratislava  2450.0
1  John Smith         IT        Brno  3900.0
2  Lucy Brown         IT  Bratislava  4200.0
[2, 3, 4] 12 10

Merging

The merge method joins two DataFrame objects on common columns, like an SQL join. We have a second file with departments.

departments.csv
department,manager,floor
IT,Robert Black,3
Sales,Jane Doe,1
Marketing,Eva Varga,2
Finance,Oliver Stone,4

There is no HR row, and the Finance department has no employees.

merge.py
import pandas as pd

emps = pd.read_csv('employees.csv')
deps = pd.read_csv('departments.csv')

merged = emps.merge(deps, on='department', how='left')
print(merged[['name', 'department', 'manager', 'floor']].head(5))

print(emps.merge(deps, on='department', how='outer', indicator=True)
      ['_merge'].value_counts())

A left join keeps all employees and adds the department data. HR employees get NaN for the manager and the floor, so the floor column becomes float.

print(emps.merge(deps, on='department', how='outer', indicator=True)
      ['_merge'].value_counts())

An outer join keeps the rows from both sides. The indicator option adds the _merge column that tells where each row came from: 10 employees have a matching department, two HR employees do not, and the Finance department has no employees.

$ python merge.py
          name department       manager  floor
0     Jane Doe      Sales      Jane Doe    1.0
1   John Smith         IT  Robert Black    3.0
2   Lucy Brown         IT  Robert Black    3.0
3  Peter Novak  Marketing     Eva Varga    2.0
4   Anna Kovac      Sales      Jane Doe    1.0
_merge
both          10
left_only      2
right_only     1
Name: count, dtype: int64

Writing CSV

The to_csv method writes a DataFrame to a CSV file.

write_csv.py
import pandas as pd

df = pd.read_csv('employees.csv')

it = df[df['department'] == 'IT'][['name', 'city', 'salary']]
it.to_csv('it_staff.csv', index=False)

with open('it_staff.csv', encoding='utf-8') as f:
    print(f.read(), end='')

We write the IT employees to a new file. With index=False, the index is not written. The salaries are written as floats, because the column has the float type; the float_format option controls their format.

$ python write_csv.py
name,city,salary
John Smith,Brno,3900.0
Lucy Brown,Bratislava,4200.0
Robert Black,Vienna,5100.0
Paul Green,Brno,4600.0

Converting to dictionaries

The to_dict method converts a DataFrame to a dictionary. The orient parameter determines the structure.

to_dict.py
import pandas as pd

df = pd.DataFrame({'name': ['Alex', 'Ronald', 'Jane'], 'age': [10, 18, 33]})

print(df.to_dict())
print(df.to_dict(orient='list'))
print(df.to_dict(orient='records'))
print(df.to_dict(orient='index'))

The default orientation maps columns to dictionaries of index and value. The list orientation maps columns to lists of values, records gives a list of rows, and index maps index labels to rows. The records format is common in JSON APIs.

$ python to_dict.py
{'name': {0: 'Alex', 1: 'Ronald', 2: 'Jane'}, 'age': {0: 10, 1: 18, 2: 33}}
{'name': ['Alex', 'Ronald', 'Jane'], 'age': [10, 18, 33]}
[{'name': 'Alex', 'age': 10}, {'name': 'Ronald', 'age': 18}, {'name': 'Jane', 'age': 33}]
{0: {'name': 'Alex', 'age': 10}, 1: {'name': 'Ronald', 'age': 18}, 2: {'name': 'Jane', 'age': 33}}

Random sample

The sample method returns random rows.

random_sample.py
import pandas as pd

df = pd.read_csv('employees.csv')

print(df.sample(3, random_state=1)[['name', 'city']])
print()
print(df.sample(frac=0.25, random_state=7)[['name', 'city']])

We select three random rows, and then a quarter of all rows. The random_state option seeds the random generator, so the selection is the same on every run.

$ python random_sample.py
          name        city
2   Lucy Brown  Bratislava
3  Peter Novak      Vienna
4   Anna Kovac        Brno

          name        city
7   Tomas Kral      Vienna
10  Sofia Ruiz      Vienna
2   Lucy Brown  Bratislava

Source

pandas documentation

What's new in pandas 3.0

In this article we have done basic data analysis with pandas. The pandas tutorials cover the library in more detail. See also Python Matplotlib, Python CSV, and Python openpyxl.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.