天天看點

Python中dataframe\ array\ list互相轉化

1 import pandas as pd
 2 import numpy as np
 3 
 4 #建立清單
 5 a1=[1,2,3]
 6 
 7 #arange函數:指定初始值、終值、步長來建立數組
 8 a2=np.arange(0,1,0.1)
 9 
10 #建立資料框
11 a3=pd.DataFrame({'a':[1,2,3],'b':[4,5,6],'c':[7,8,9]})      
#1、list 轉化成array矩陣
b1 = np.array(a1).T
Out[30]: array([1, 2, 3])     
           

  

#2、array轉化成dataframe
b2 = pd.DataFrame(a2)
Out[32]: 
     0
0  0.0
1  0.1
2  0.2
3  0.3
4  0.4
5  0.5
6  0.6
7  0.7
8  0.8
9  0.9
b2.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 10 entries, 0 to 9
Data columns (total 1 columns):
0    10 non-null float64
dtypes: float64(1)
memory usage: 160.0 bytes
           

  

#3、把Pandas中的dataframe轉成numpy中的array
b3=a3.values

Out[35]: 
array([[1, 4, 7],
       [2, 5, 8],
       [3, 6, 9]], dtype=int64)
           

  

轉載于:https://www.cnblogs.com/Christina-Notebook/p/10100903.html

繼續閱讀