Python读取csv文件,并加载其中的几行几列

loc只能通过index(行)和columns(列)索引名来取,不能用数字索引,一般的loc的行取可用数字索引,但列名不可用数字索引
df.loc[‘one’,‘a’]#one行,a列
df.loc[‘one’:‘two’,‘a’]#one到two行,a列
df.loc[‘one’:‘two’,‘a’:‘c’]#one到two行,a到c列
df.loc[‘one’:‘two’,[‘a’,‘c’]]#one到two行,ac列

import pandas as pd
import numpy as np
col1 = np.arange(0,4348,1)
Final_metadata = pd.read_csv('D:\Pycharm\PythonStudy\PCA\Final_metadata_4347.csv', usecols=col1)                       # 取0-4347列
x1 = Final_metadata.loc[0:0]        # (1, 4348)
x2 = Final_metadata.loc[33:344]     # (312, 4348)
x = pd.concat([x1, x2],axis=0)      # (313, 4348)
print(x)
x.to_csv('1.csv', index=False) #False作用是去除最左边生成的一列0,1,2··

运用python读取csv文件某几列
iloc只能用数字索引,不能用索引名
df.iloc[0]#第0行
df.iloc[0:2,0:2]#0、1行,0、1列
df.iloc[[0,2],[1,2,3]]#第0、2行,1、2、3列

import pandas as pd
data=pd.read_csv('../PCA/4347_final_relative_abundances_new.csv')
print(data)
x1 = data.iloc[0:0,200:300]
x2 = data.iloc[33:344,200:300]
x = pd.concat([x1, x2],axis=0)
print(x)

python将txt文件转为csv文件

import pandas as pd
data=pd.read_csv('../PCA/4347_final_relative_abundances.txt',sep='\t')
print(data)
data.to_csv('4347_final_relative_abundances_new.csv', index=False)

你可能感兴趣的:(python)