引言
list类为python自带的数据类型,常用的模块有numpy, pandas, tensorflow,他们拥有自己的数据类型,并且可以相互转换,以下对四种数据类型转换作出说明。
1. list转换为其他类型
import numpy as np
import pandas as pd
import tensorflow as tf
list_ = [1, 2, 3]
print(list_)
list2np = np.array(list_)
print(list2np)
list2pd = pd.Series(list_)
print(list2pd)
list2tf = tf.constant(list_)
print(list2tf)
输出为:
[1, 2, 3]
[1 2 3]
0 1
1 2
2 3
dtype: int64
tf.Tensor([1 2 3], shape=(3,), dtype=int32)
2. numpy转换为其他类型
import numpy as np
import pandas as pd
import tensorflow as tf
np_ = np.array([1, 2, 3])
print(np_)
np2list = np_.tolist()
np2list_ = list(np_)
print(np2list, np2list_)
np2pd = pd.Series(np_)
print(np2pd)
np2tf = tf.constant(np_)
print(np2tf)
输出为:
[1 2 3]
[1, 2, 3] [1, 2, 3]
0 1
1 2
2 3
dtype: int32
tf.Tensor([1 2 3], shape=(3,), dtype=int32)
3. pandas转换为其他类型
import numpy as np
import pandas as pd
import tensorflow as tf
pd_ = pd.Series([1, 2, 3])
print(pd_)
pd2list = pd_.tolist()
pd2list_ = list(pd_)
print(pd2list, pd2list_)
pd2pd = pd.Series(pd_)
print(pd2pd)
pd2tf = tf.constant(pd_)
print(pd2tf)
输出为:
0 1
1 2
2 3
dtype: int64
[1, 2, 3] [1, 2, 3]
[1 2 3]
tf.Tensor([1 2 3], shape=(3,), dtype=int64)
4. tensorflow转换为其他类型
import numpy as np
import pandas as pd
import tensorflow as tf
tf_ = tf.constant([1, 2, 3])
print(tf_)
# tf2list = tf_.tolist() # 报错
tf2list_ = list(tf_)
print(tf2list_)
tf2np = np.array(tf_)
print(tf2np)
tf2pd = pd.Series(tf_)
print(tf2pd)
输出为:
tf.Tensor([1 2 3], shape=(3,), dtype=int32)
[<tf.Tensor: shape=(), dtype=int32, numpy=1>, <tf.Tensor: shape=(), dtype=int32, numpy=2>, <tf.Tensor: shape=(), dtype=int32, numpy=3>]
[1 2 3]
0 1
1 2
2 3
dtype: int32