list,numpy,panads,tensorflow数据类型转换

引言

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值