Pandas Numpy
# Pandas and NumPy Integration
Pandas is built on top of NumPy, and they are tightly integrated. Understanding their interaction can lead to more efficient data processing and scientific computing.
* * *
## Conversion Between Data Structures
### Converting DataFrame/Series to NumPy Arrays
## Example
```python
import pandas as pd
import numpy as np
# Convert DataFrame to NumPy array
df = pd.DataFrame({
"A": [1,2,3],
"B": [4,5,6]
})
arr = df.to_numpy()
print("DataFrame to array:")
print(arr)
print(f"Type: {type(arr)}")
print()
# Convert Series to array
s = pd.Series([1,2,3])
arr = s.values # or s.to_numpy()
print("Series to array:")
print(arr)
print()
# Convert NumPy array to DataFrame
arr = np.array([[1,2],[3,4],[5,6]])
df = pd.DataFrame(arr, columns=["A","B"])
print("Array to DataFrame:")
print(df)
* * *
## Using NumPy Functions in Pandas
## Example
```python
import pandas as pd
import numpy as np
# Using NumPy functions with Pandas objects
s = pd.Series([1, 2, 3, 4, 5])
result = np.sqrt(s)
print("Square root of Series:")
print(result)
print()
# Using NumPy functions on DataFrame
df = pd.DataFrame({'A': [1, 4, 9], 'B': [16, 25, 36]})
result = np.log(df)
print("Natural logarithm of DataFrame:")
print(result)
## Advanced Usage
You can also use NumPy's advanced functions directly on Pandas objects:
```python
import pandas as pd
import numpy as np
# Using NumPy's linear algebra functions
df = pd.DataFrame(np.random.randn(3, 3))
print("Original DataFrame:")
print(df)
print()
# Compute determinant
det = np.linalg.det(df.values)
print(f"Determinant: {det}")
print()
# Compute eigenvalues
eigenvals = np.linalg.eigvals(df.values)
print("Eigenvalues:")
print(eigenvals)
This integration allows you to leverage the powerful numerical computing capabilities of NumPy while working with the high-level data structures provided by Pandas.
YouTip