import numpy as np
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
from numpy array to pandas DataFrame/Series
# Creating a numpy array
= np.arange(6, 15, 1) + 0.2
a print(a.shape)
a
(9,)
array([ 6.2, 7.2, 8.2, 9.2, 10.2, 11.2, 12.2, 13.2, 14.2])
= pd.Series(a)
s_from_np s_from_np
0 6.2
1 7.2
2 8.2
3 9.2
4 10.2
5 11.2
6 12.2
7 13.2
8 14.2
dtype: float64
s_from_np.array
<PandasArray>
[6.2, 7.2, 8.2, 9.2, 10.2, 11.2, 12.2, 13.2, 14.2]
Length: 9, dtype: float64
s_from_np.to_numpy()
array([ 6.2, 7.2, 8.2, 9.2, 10.2, 11.2, 12.2, 13.2, 14.2])
= pd.Series(['a', 'b', 'c'])
s_from_list s_from_list
0 a
1 b
2 c
dtype: object
s_from_list.array
<PandasArray>
['a', 'b', 'c']
Length: 3, dtype: object
= np.random.normal(size=(8, 2))
A2d A2d.shape
(8, 2)
= pd.DataFrame(A2d)
df_from_np 3:7. :] df_from_np.loc[
0 | 1 | |
---|---|---|
3 | 0.604053 | 0.419030 |
4 | -1.416968 | 0.344342 |
5 | 0.331019 | -0.322755 |
6 | 1.425032 | 1.385376 |
7 | -0.910557 | 1.020370 |
df_from_np
0 | 1 | |
---|---|---|
0 | -1.925208 | -1.376625 |
1 | 3.023642 | -0.044192 |
2 | 0.471226 | 0.636105 |
3 | 0.604053 | 0.419030 |
4 | -1.416968 | 0.344342 |
5 | 0.331019 | -0.322755 |
6 | 1.425032 | 1.385376 |
7 | -0.910557 | 1.020370 |
Changing indices
= list('abcdefgh')
indices indices
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
= pd.DataFrame(A2d, index=indices)
df_from_np df_from_np
0 | 1 | |
---|---|---|
a | -1.925208 | -1.376625 |
b | 3.023642 | -0.044192 |
c | 0.471226 | 0.636105 |
d | 0.604053 | 0.419030 |
e | -1.416968 | 0.344342 |
f | 0.331019 | -0.322755 |
g | 1.425032 | 1.385376 |
h | -0.910557 | 1.020370 |
Changing indices
= list('abcdefgh') indices
= ['firstCol']
df_from_np.columns df_from_np
ValueError: Length mismatch: Expected axis has 2 elements, new values have 1 elements
df_from_np.array
AttributeError: 'DataFrame' object has no attribute 'array'
df_from_np.to_numpy()
array([[-1.9252077 , -1.37662472],
[ 3.02364168, -0.04419207],
[ 0.47122622, 0.63610455],
[ 0.60405305, 0.41903048],
[-1.4169681 , 0.34434206],
[ 0.33101902, -0.32275461],
[ 1.4250323 , 1.38537568],
[-0.91055686, 1.02037012]])