Pandas Data Structures - DataFrame
DataFrame is another core data structure in Pandas, similar to a two-dimensional table or a data table in a database.
DataFrame is a tabular data structure containing an ordered set of columns, each of which can have a different value type (numeric, string, boolean).
DataFrame has both a row index and a column index; it can be viewed as a dictionary of Series (sharing a common index).
DataFrame provides various functions for data access, filtering, slicing, merging, reshaping, aggregation, and transformation.
DataFrame is a very flexible and powerful data structure widely used for tasks such as data analysis, cleaning, transformation, and visualization.
Features of DataFrame:
-
Two-dimensional structure:
DataFrameIt is a two-dimensional table that can be viewed as an Excel spreadsheet or an SQL table, with rows and columns. It can be regarded as a dictionary of multipleSeriesobjects. -
Column data types: Different columns can contain different data types, such as integers, floats, strings, or Python objects.
-
Index:
DataFrameIt can have a row index and a column index, similar to row numbers and column labels in Excel. -
Variable size: Columns can be added and deleted, similar to a Python dictionary.
-
Automatic alignment: When performing arithmetic operations or data alignment,
DataFrameindices are automatically aligned. -
Handling missing data:
DataFrameIt can contain missing data; Pandas usesNaN(Not a Number) to represent it. -
Data operations: Supports operations such as data slicing, indexing, and subsetting.
-
Time series support:
DataFrameIt has special support for time series data, making it easy to slice, index, and manipulate time data. -
Rich data access capabilities: Through
.loc、.ilocand.query()methods allow flexible access to and filtering of data. -
Flexible data processing capabilities: Including data merging, reshaping, pivoting, grouping, and aggregation.
-
Data visualization: Although
DataFrameIt is not a visualization tool by itself, but it can be used together with visualization libraries such as Matplotlib or Seaborn to perform data visualization. -
Efficient data input and output: It can conveniently read and write data, supporting multiple formats such as CSV, Excel, SQL databases, and HDF5.
-
Descriptive statistics: It provides a series of methods for calculating descriptive statistics, such as
.describe()、.mean()、.sum(), etc. -
Flexible data alignment and integration: It can easily be merged, joined, or updated with other
DataFrameorSeriesobjects. -
Transformation functions: It can transform values in a dataset, for example, using the
.apply()method to apply custom functions. -
Rolling window and time series analysis: It supports rolling window statistics and time series analysis on datasets.


The DataFrame constructor is as follows:
pandas.DataFrame(data=None, index=None, columns=None, dtype=None, copy=False)
Parameter Description:
data: The data part of the DataFrame, which can be a dictionary, a two-dimensional array, a Series, a DataFrame, or other objects convertible to a DataFrame. If this parameter is not provided, an empty DataFrame is created.index: The row index of the DataFrame, used to identify each row of data. It can be a list, an array, an Index object, and so on. If this parameter is not provided, a default integer index is created.columns: The column index of the DataFrame, used to identify each column of data. It can be a list, an array, an Index object, and so on. If this parameter is not provided, a default integer index is created.dtype: Specifies the data type of the DataFrame. It can be a NumPy data type, such asnp.int64、np.float64, etc. If this parameter is not provided, the data type is inferred automatically from the data.copy: Whether to copy the data. The default is False, meaning the data is not copied. If set to True, the input data is copied.
A Pandas DataFrame is a two-dimensional array-like structure, similar to a two-dimensional array.
Example - Creating from a list
import
pandas
as
pd
data
=
[
[
'Google'
,
10
]
,
[
'Runoob'
,
12
]
,
[
'Wiki'
,
13
]
]
Create a DataFrame
df
=
pd.
DataFrame
(
data
,
columns
=
[
'Site'
,
'Age'
]
)
Use the astype method to set the data type of each column
df
[
'Site'
]
=
df
[
'Site'
]
.
astype
(
str
)
df
[
'Age'
]
=
df
[
'Age'
]
.
astype
(
float
)
(
df
)
You can also create one using a dictionary:
Example - Creating from a dictionary
import
pandas
as
pd
data
=
{
'Site'
:
[
'Google'
,
'Runoob'
,
'Wiki'
]
,
'Age'
:
[
10
,
12
,
13
]
}
df
=
pd.
DataFrame
(
data
)
(
df
)
The output is as follows:

The following example creates from ndarrays; the ndarrays must have the same length. If an index is passed, its length should equal the length of the arrays. If no index is passed, by default the index will be range(n), where n is the array length.
For ndarrays, you can refer to:NumPy Ndarray Object
Example - Creating from ndarrays
import
numpy
as
np
import
pandas
as
pd
Create a two-dimensional ndarray containing websites and ages
ndarray_data
=
np.
array
(
[
[
'Google'
,
10
]
,
[
'Runoob'
,
12
]
,
[
'Wiki'
,
13
]
]
)
Create a DataFrame using the DataFrame constructor
df
=
pd.
DataFrame
(
ndarray_data
,
columns
=
[
'Site'
,
'Age'
]
)
Print the DataFrame
(
df
)
The output is as follows:

From the output above, we can see that the DataFrame data type is a table containing rows and columns:

You can also use a dictionary (key/value), where the key of the dictionary is the column name:
Example - Creating from a dictionary
import
pandas
as
pd
data
=
[
{
'a'
:
1
,
'b'
:
2
}
,
{
'a'
:
5
,
'b'
:
10
,
'c'
:
20
}
]
df
=
pd.
DataFrame
(
data
)
(
df
)
The output is:
a b c
0 1 2 NaN
1 5 10 20.0
Missing corresponding data is NaN。
Pandas can use the loc attribute to return data for a specified row. If no index is set, the index of the first row is 0, the index of the second row is 1, and so on:
Example
import
pandas
as
pd
data
=
{
"calories"
:
[
420
,
380
,
390
]
,
"duration"
:
[
50
,
40
,
45
]
}
Load data into a DataFrame object
df
=
pd.
DataFrame
(
data
)
Return the first row
(
df.
loc
[
0
]
)
Return the second row
(
df.
loc
[
1
]
)
The output is as follows:
calories 420
duration 50
Name: 0, dtype: int64
calories 380
duration 40
Name: 1, dtype: int64
**Note:** The returned result is actually a Pandas Series.
You can also return multiple rows using the [[ ... ]] format, where ... is the index of each row, separated by commas:
Example
import
pandas
as
pd
data
=
{
"calories"
:
[
420
,
380
,
390
]
,
"duration"
:
[
50
,
40
,
45
]
}
Load data into a DataFrame object
df
=
pd.
DataFrame
(
data
)
Return the first and second rows
(
df.
loc
[
[
0
,
1
]
]
)
The output is:
calories duration
0 420 50
1 380 40
**Note:** The returned result is actually a Pandas DataFrame.
We can specify index values, as in the following example:
Example
import
pandas
as
pd
data
=
{
"calories"
:
[
420
,
380
,
390
]
,
"duration"
:
[
50
,
40
,
45
]
}
df
=
pd.
DataFrame
(
data
,
index
=
[
"day1"
,
"day2"
,
"day3"
]
)
(
df
)
The output is:
calories duration
day1 420 50
day2 380 40
day3 390 45
Pandas can use the loc attribute to return a row corresponding to a specified index:
Example
import
pandas
as
pd
data
=
{
"calories"
:
[
420
,
380
,
390
]
,
"duration"
:
[
50
,
40
,
45
]
}
df
=
pd.
DataFrame
(
data
,
index
=
[
"day1"
,
"day2"
,
"day3"
]
)
Specify the index
(
df.
loc
[
"day2"
]
)
The output is:
calories 380
duration 40
Name: day2, dtype: int64
DataFrame methods
The common operations and methods of DataFrame are shown in the table below:
| Method Name | Description |
|---|---|
head(n) |
Return the first n rows of the DataFrame (the first 5 rows by default) |
tail(n) |
Return the last n rows of the DataFrame (the last 5 rows by default) |
info() |
Display brief information about the DataFrame, including column names, data types, the number of non-null values, and so on |
describe() |
Return statistical information for the numerical columns of the DataFrame, such as mean, standard deviation, minimum, and so on |
shape |
Return the number of rows and columns of the DataFrame (number of rows, number of columns) |
columns |
Return all column names of the DataFrame |
index |
Return the row index of the DataFrame |
dtypes |
Return the numerical data type of each column |
sort_values(by) |
Sort by a specified column |
sort_index() |
Sort by row index |
dropna() |
Drop rows or columns containing missing values (NaN) |
fillna(value) |
Fill missing values with a specified value |
isnull() |
Detect missing values, returning a boolean DataFrame |
notnull() |
Detect non-missing values, returning a boolean DataFrame |
loc[] |
Select data by label index |
iloc[] |
Select data by position index |
at[] |
Access a single element in a DataFrame (more efficient than loc[] ) |
iat[] |
Access a single element in a DataFrame (more efficient than iloc[] ) |
apply(func) |
Apply a function to a DataFrame or Series |
applymap(func) |
Apply a function to each element of a DataFrame (DataFrame only) |
groupby(by) |
Grouping operation, used to group by a column for summary statistics |
pivot_table() |
Create a pivot table |
merge() |
Merge multiple DataFrames (similar to a SQL JOIN operation) |
concat() |
Concatenate multiple DataFrames by row or by column |
to_csv() |
Export the DataFrame to a CSV file |
to_excel() |
Export the DataFrame to an Excel file |
to_json() |
Export the DataFrame to JSON format |
to_sql() |
Export the DataFrame to a SQL database |
query() |
Query a DataFrame using SQL-style syntax |
duplicated() |
Return a boolean DataFrame indicating whether each row is a duplicate |
drop_duplicates() |
Drop duplicate rows |
set_index() |
Set the index of the DataFrame |
reset_index() |
Reset the index of the DataFrame |
transpose() |
Transpose the DataFrame (swap rows and columns) |
Example
import
pandas
as
pd
Create DataFrame
data
=
{
'Name'
:
[
'Alice'
,
'Bob'
,
'Charlie'
,
'David'
]
,
'Age'
:
[
25
,
30
,
35
,
40
]
,
'City'
:
[
'New York'
,
'Los Angeles'
,
'Chicago'
,
'Houston'
]
}
df
=
pd.
DataFrame
(
data
)
View the first two rows of data
(
df.
head
(
2
)
)
View basic information about the DataFrame
(
df.
info
(
)
)
Get descriptive statistics
(
df.
describe
(
)
)
Sort by age
df_sorted
=
df.
sort_values
(
by
=
'Age'
,
ascending
=
False
)
(
df_sorted
)
Select specified columns
(
df
[
[
'Name'
,
'Age'
]
]
)
Select rows by index
(
df.
iloc
[
1
:
3
]
)
Select the second to third rows (by position)
Select rows by label
(
df.
loc
[
1
:
2
]
)
Select the second to third rows (by label)
Compute grouped statistics (group by city and calculate the average age)
(
df.
groupby
(
'City'
)
[
'Age'
]
.
mean
(
)
)
Handle missing values (fill missing values)
df
[
'Age'
]
=
df
[
'Age'
]
.
fillna
(
30
)
Export to a CSV file
df.
to_csv
(
'output.csv'
,
index
=
False
)
The output is:
# View the first two lines of data
Name Age City
0 Alice 25 New York
1 Bob 30 Los Angeles
# View basic information of the DataFrame
RangeIndex: 4 entries, 0 to 3
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Name 4 non-null object
1 Age 4 non-null int64
2 City 4 non-null object
dtypes: int64(1), object(2)
memory usage: 148.0+ bytes
# Get descriptive statistics
Age
count 4.000000
mean 32.500000
std 6.454972
min 25.000000
25% 27.500000
50% 32.500000
75% 37.500000
max 40.000000
# Sort by age
Name Age City
3 David 40 Houston
2 Charlie 35 Chicago
1 Bob 30 Los Angeles
0 Alice 25 New York
# Select rows by tag
Name Age City
1 Bob 30 Los Angeles
2 Charlie 35 Chicago
# Calculate grouped statistics (group by city, calculate average age)
City
Chicago 35.0
Houston 40.0
Los Angeles 30.0
New York 25.0
Name: Age, dtype: float64
More information about DataFrame
Create DataFrame
**Creating from a dictionary:** The keys of the dictionary become column names, and the values become column data.
Example
import
pandas
as
pd
Create a DataFrame from a dictionary
df
=
pd.
DataFrame
(
{
'Column1'
:
[
1
,
2
,
3
]
,
'Column2'
:
[
4
,
5
,
6
]
}
)
**Creating from a list of lists:** The outer list represents rows, and the inner list represents columns.
Create a DataFrame from a list of lists
Example
df
=
pd.
DataFrame
(
[
[
1
,
2
,
3
]
,
[
4
,
5
,
6
]
,
[
7
,
8
,
9
]
]
,
columns
=
[
'Column1'
,
'Column2'
,
'Column3'
]
)
**Creating from a NumPy array:** Provide a two-dimensional NumPy array.
Example
import
numpy
as
np
Create a DataFrame from a NumPy array
df
=
pd.
DataFrame
(
np.
array
(
[
[
1
,
2
,
3
]
,
[
4
,
5
,
6
]
,
[
7
,
8
,
9
]
]
)
)
**Creating a DataFrame from a Series:** Create via pd.Series().
Example
Create a DataFrame from a Series
s1
=
pd.
Series
(
[
'Alice'
,
'Bob'
,
'Charlie'
]
)
s2
=
pd.
Series
(
[
25
,
30
,
35
]
)
s3
=
pd.
Series
(
[
'New York'
,
'Los Angeles'
,
'Chicago'
]
)
df
=
pd.
DataFrame
(
{
'Name'
: s1
,
'Age'
: s2
,
'City'
: s3
}
)
Attributes and methods of DataFrame
A DataFrame object has many attributes and methods for data manipulation, indexing, and processing, such as shape, columns, index, head(), tail(), info(), describe(), mean(), sum(), and so on.
Example
Attributes and methods of DataFrame
(
df.
shape
)
Shape
(
df.
columns
)
Column Name
(
df.
index
)
Index
(
df.
head
(
)
)
The first few rows of data, the first 5 rows by default
(
df.
tail
(
)
)
The last few rows of data, the last 5 rows by default
(
df.
info
(
)
)
Data information
(
df.
describe
(
)
)
Descriptive statistics
(
df.
mean
(
)
)
Compute the mean
(
df.
sum
(
)
)
Sum
Accessing DataFrame elements
**Accessing columns:** Use the column name as an attribute or access via .loc[] and .iloc[]; you can also use label or position indexing.
Example
Access by column name
(
df
[
'Column1'
]
)
Access by attribute
(
df.
Name
)
Access via .loc[]
(
df.
loc
[
:
,
'Column1'
]
)
Access via .iloc[]
(
df.
iloc
[
:
,
0
]
)
Assume 'Column1' is the first column
Access a single element
(
df
[
'Name'
]
[
0
]
)
**Accessing rows:** Use the row's label and .loc[] for access.
Example
Access by row label
(
df.
loc
[
0
,
'Column1'
]
)
Modifying DataFrame
**Modifying column data:** Assign a value directly to the column.
df['Column1'] = [10, 11, 12]
**Adding a new column:** Assign a value to the new column.
df['NewColumn'] = [100, 200, 300]
**Adding a new row:** Use the loc, append, or concat method.
Example
Use loc to add a new row for a specific index
df.
loc
[
3
]
=
[
13
,
14
,
15
,
16
]
Use append to add a new row to the end
new_row
=
{
'Column1'
:
13
,
'Column2'
:
14
,
'NewColumn'
:
16
}
df
=
df.
append
(
new_row
,
ignore_index
=
True
)
**Note:**append() The method has been marked as deprecated in pandas version 1.4.0 and will be removed in a future version. The official recommendation is to use concat() as an alternative for merging data.
The concat() method is used to merge two or more DataFrames. When you want to add a row to another DataFrame, you can treat the new row as a new DataFrame and then use concat():
Example
Add a new row using concat
new_row
=
pd.
DataFrame
(
[
[
4
,
7
]
]
,
columns
=
[
'A'
,
'B'
]
)
Create a DataFrame containing only the new row
df
=
pd.
concat
(
[
df
,
new_row
]
,
ignore_index
=
True
)
Add the new row to the original DataFrame
(
df
)
Deleting DataFrame elements
**Dropping columns:** Use the drop method.
df_dropped = df.drop('Column1', axis=1)
**Dropping rows:** Also use the drop method.
df_dropped = df.drop(0) # 删除索引为 0 的行
Statistical analysis of DataFrame
**Descriptive statistics:** Use .describe() to view a statistical summary of the numerical columns.
df.describe()
**Calculating statistics:** Use aggregate functions such as .sum(), .mean(), .max(), and so on.
df['Column1'].sum()
df.mean()
Index operations on DataFrame
**Resetting the index:** Use .reset_index().
df_reset = df.reset_index(drop=True)
**Setting the index:** Use .set_index().
df_set = df.set_index('Column1')
Boolean indexing of DataFrame
Using boolean expressions: Filter the DataFrame based on conditions.
df[df['Column1'] > 2]
Data types of DataFrame
View data types: Use the dtypes attribute.
df.dtypes
**Converting data types:** Use the astype method.
df['Column1'] = df['Column1'].astype('float64')
Merging and splitting DataFrame
**Merging:** Use the concat or merge method.
# 纵向合并
pd.concat([df1, df2], ignore_index=True)
# Horizontal merge
pd.merge(df1, df2, on='Column1')
**Splitting:** Use pivot, melt, or custom functions.
# Convert long format to wide format
df_pivot = df.pivot(index='Column1', columns='Column2', values='Column3')
# Wide to long format
df_melt = df.melt(id_vars='Column1', value_vars=['Column2', 'Column3'])
Indexing and slicing
DataFrame supports indexing and slicing operations on rows and columns.
Example
Indexing and slicing
(
df
[
[
'Name'
,
'Age'
]
]
)
Extract multiple columns
(
df
[
1
:
3
]
)
Slice rows
(
df.
loc
[
:
,
'Name'
]
)
Extract a single column
(
df.
loc
[
1
:
2
,
[
'Name'
,
'Age'
]
]
)
Extract specified rows and columns by label indexing
(
df.
iloc
[
:
,
1
:
]
)
Extract specified columns by position indexing
Notes
DataFrameIt is a flexible data structure that can hold columns of different data types.- Column names and row indices can be strings, integers, and so on.
DataFrameData can be selected, filtered, modified, and analyzed in a variety of ways.- Through operations on
DataFrame, you can perform data cleaning, transformation, analysis, visualization, and other tasks.