Pandas Combined with NumPy
Pandas is built on NumPy and the two are tightly integrated. Understanding how they interact enables more efficient data processing and scientific computing.
Converting between them
Converting between DataFrame/Series and NumPy
Example
import
pandas
as
pd
import
numpy
as
np
Convert a DataFrame to a NumPy array
df
=
pd.
DataFrame
(
{
"A"
:
[
1
,
2
,
3
]
,
"B"
:
[
4
,
5
,
6
]
}
)
arr
=
df.
to_numpy
(
)
(
"DataFrame converted to array:"
)
(
arr
)
(
f
"Type: {type(arr)}"
)
(
)
Convert a Series to an array
s
=
pd.
Series
(
[
1
,
2
,
3
]
)
arr
=
s.
values
or s.to_numpy()
(
"Series converted to array:"
)
(
arr
)
(
)
Convert NumPy to DataFrame
arr
=
np.
array
(
[
[
1
,
2
]
,
[
3
,
4
]
,
[
5
,
6
]
]
)
df
=
pd.
DataFrame
(
arr
,
columns
=
[
"A"
,
"B"
]
)
(
"Array converted to DataFrame:"
)
(
df
)
Using NumPy functions in Pandas
Example
import
pandas
as
pd
import
numpy
as
np
s
=
pd.
Series
(
[
1
,
2
,
3
,
4
,
5
]
)
Use NumPy functions
(
"Absolute value:"
,
np.
abs
(
s
)
)
(
"Square root:"
,
np.
sqrt
(
s
)
)
(
"Exponential:"
,
np.
exp
(
s
)
)
(
"Logarithm:"
,
np.
log
(
s
)
)
(
)
Conditional filtering
(
"Values greater than 3:"
)
(
s
[
s
3
]
)
Vectorized operations
Example
import
pandas
as
pd
import
numpy
as
np
df
=
pd.
DataFrame
(
{
"A"
:
[
1
,
2
,
3
]
,
"B"
:
[
4
,
5
,
6
]
}
)
Vectorized operations
(
"A + B:"
,
(
df
[
"A"
]
- df
[
"B"
]
)
.
tolist
(
)
)
(
"A * B:"
,
(
df
[
"A"
]
- df
[
"B"
]
)
.
tolist
(
)
)
(
"A > B:"
,
(
df
[
"A"
]
df
[
"B"
]
)
.
tolist
(
)
)
(
)
Using apply for element-wise computation
result
=
df.
apply
(
lambda
x: np.
multiply
(
x
,
2
)
)
(
"Each element * 2:"
)
(
result
)
Numerical computation techniques
Example
import
pandas
as
pd
import
numpy
as
np
df
=
pd.
DataFrame
(
{
"A"
:
[
1
,
2
,
3
,
4
,
5
]
,
"B"
:
[
10
,
20
,
30
,
40
,
50
]
}
)
Calculate the percentage change of A relative to B
df
[
"Change Rate"
]
=
np.
divide
(
df
[
"A"
]
,
df
[
"B"
]
,
where
=
df
[
"B"
]
!=
0
)
100
(
"Percentage change:"
)
(
df
)
(
)
Using np.where for conditional assignment
df
[
"Label"
]
=
np.
where
(
df
[
"A"
]
3
,
"Large"
,
"Small"
)
(
"Conditional labels:"
)
(
df
)
Statistical computation
Example
import
pandas
as
pd
import
numpy
as
np
s
=
pd.
Series
(
[
1
,
2
,
3
,
4
,
5
,
6
,
7
,
8
,
9
,
10
]
)
NumPy statistical functions
(
f
"Mean: {np.mean(s):.2f}"
)
(
f
"Standard deviation: {np.std(s):.2f}"
)
(
f
"Maximum: {np.max(s)}"
)
(
f
"Minimum: {np.min(s)}"
)
(
)
Median
(
f
"Median: {np.median(s)}"
)
The deep integration of Pandas and NumPy makes complex data processing simple and efficient.