不同格式文件之间的相互转化

1、npy转变为txt

import numpy as np
import sys

np.set_printoptions(threshold=sys.maxsize)
 
boxes=np.load('E:/kepler/all特征.npy',allow_pickle=True)

np.savetxt('E:/kepler/all特征.txt',boxes,fmt='%s',newline='\n')

2、txt转变为csv


import csv

with open('E:/kepler/all特征.csv', 'w+', newline='') as csvfile:
    spamwriter = csv.writer(csvfile, dialect='excel')
    # 读要转换的txt文件,文件每行各词间以字符分隔
    with open('E:/kepler/all特征.txt', 'r', encoding='utf-8') as filein:
        for line in filein:
            line_list = line.strip('\n').split(' ')   #我这里的数据之间是以tab间隔的
            spamwriter.writerow(line_list)

3、csv转变为npy

import pandas as pd
import numpy as np

# 先用pandas读入csv
data = pd.read_csv("E:/kepler/all特征.csv")
print(data.shape)
# 再使用numpy保存为npy
np.save("E:/kepler/all特征s.npy", data)

4、npy格式转变为datafram

p=np.load('E:/kepler/all特征s.npy',allow_pickle=True)
print(p.shape)
df1 = pd.DataFrame(p)

其他

1、给datafram添加列名

p=np.load('E:/kepler/all特征s.npy',allow_pickle=True)
print(p.shape)
df1 = pd.DataFrame(p)

df1.columns=['GMAG','RMAG','IMAG','ZMAG','D51MAG','JMAG','HMAG','KMAG','KEPMAG',
            'GRCOLOR','JKCOLOR','GKCOLOR','TEFF','LOGG','FEH','EBMINUSV','AV','RADIUS','label']

print(df1)

2、插入数据

df2 = pd.DataFrame(np.insert(df1.values, 0, values=df[0:1], axis=0))

#df1是初始的dataframe  df2是修改后

#0是第1行,首行添加 axis=0代表是行,axis=1代表是列

#values是需要插入的数据

暂时就这些吧!

你可能感兴趣的:(python,人工智能,机器学习)