相关参数
a = np.array(range(0, 12)).reshape(3, 4)
b = np.array(range(0, 10))
print(a)
df = pd.DataFrame(a, index=list("ABC"), columns=list("WXYZ")) # DataFrame为二维数组
print(df)
df.to_csv('Result.csv', sep=";", na_rep="NA", header=0, index=0, columns=list('WZ'))
df.to_csv('Result3.csv', na_rep="NA", header=1, index=1, columns=['Z'])
df.to_csv('D:/PycharmProjects/untitled/数据分析/测试/Result2.csv')
print("------------------------------")
se = pd.Series(b, index=list("ABCDEFGHIG")) # Series为一维数组
print(se)
se.to_csv('reason.csv')
输出:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
W X Y Z
A 0 1 2 3
B 4 5 6 7
C 8 9 10 11
------------------------------
A 0
B 1
C 2
D 3
E 4
F 5
G 6
H 7
I 8
G 9
dtype: int32
相应的DataFrame和Series还有:
def getdistmat(coordinates):
"""
根据坐标,得出城市之间的距离矩阵
:param coordinates:
:return: distmat
"""
num = 436
# print(num)
distmat = np.zeros((num, num)) # 打印一个52行52列的二维数组
for i in range(num):
for j in range(i, num):
distmat[i][j] = distmat[j][i] = geodesic((rsu_set[i]), (rsu_set[j])).m
return distmat # distmat[i][j] = distmat[j][i]表示城市i和j距离
data1 = pd.DataFrame(getdistmat(rsu_set))
data1.to_csv('D:/PycharmProjects/untitled/paper/rsu_dis.csv')
df = pd.read_csv("./rsu_dis.csv", header=0, index_col=0)
# 注意看:打印的df结果、转化为csv后、因为dataframe行索引和列索引
# 注意看:怎么读取转化的二维数组
print(df)
distance_matrix = df.values
print(distance_matrix)
输出
0 1 ... 434 435
0 0.000000 3975.471457 ... 4127.864811 17264.013404
.. ... ... ... ... ...
435 17264.013404 21154.198618 ... 15911.135794 0.000000
[436 rows x 436 columns]
[[ 0. 3975.47145739 4220.34792082 ... 8422.71719903
4127.86481104 17264.01340402]
[ 3975.47145739 0. 5939.86488997 ... 11278.26042049
6323.51409593 21154.19861787]
[ 4127.86481104 6323.51409593 713.56697923 ... 4975.14520999
0. 15911.13579376]
[17264.01340402 21154.19861787 16602.04503987 ... 12045.76122016
15911.13579376 0. ]]
data = "D:/PycharmProjects/untitled/数据分析/data.csv"
np_data= np.loadtxt(data, dtype="float", delimiter="/", skiprows=1, usecols=[0, 1])
上面的代码中已经写有Numpy转换数组的格式了,下面直接讲解pandas转Numpy数组
# DataFrame转Numpy数组
df = pd.DataFrame(np.arange(12).reshape(3, 4))
# df.as_matrix() # 此方法已经淘汰
arr = df.values
print(df)
print("--------------------------")
print(arr)
输出:
0 1 2 3
0 0 1 2 3
1 4 5 6 7
2 8 9 10 11
--------------------------
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
同理:Series转数组也可以通过values实现。
# Series转Numpy数组
data = [['A', 10],
['B', 11]]
result = pd.DataFrame(data, columns=['fla', 'val'])
arr2 = result['val'].values
print(data)
print(result)
print(arr2)
print("--------------------------")
data2 = pd.Series([1, 2, 3])
arr3 = data2.values
print(arr3)
输出:
[['A', 10], ['B', 11]]
fla val
0 A 10
1 B 11
[10 11]
--------------------------
[1 2 3]