python文件の操作
作者:互联网
tsv文件读取:
import pandas as pd
train=pd.read_csv('test.tsv', sep='\t')
如果读取tsv已有表头:
train=pd.read_csv('test.tsv', sep='\t', header=0)
如果已有主键列:
train=pd.read_csv('test.tsv', sep='\t', header=0, index_col='id')
原文地址:https://zgljl2012.com/python-pandasdu-qu-tsvwen-jian/
python pandas读取前十行:
import pandas as pd
data=pd.read_csv('./data/chipotle.tsv', sep='\t',nrows=10)
获取pandas的列数:
import pandas as pd
data=pd.read_csv('./data/chipotle.tsv', sep='\t')
data.shape[1]
获取pandas的行数:
import pandas as pd
data=pd.read_csv('./data/chipotle.tsv', sep='\t')
data.shape[0]#或者:len(data)
打印全部列名
import pandas as pd
data=pd.read_csv('./data/chipotle.tsv', sep='\t')
#1:
list(data)
#2:
[column for column in data]
#3:(返回的是array)
data.columns.values
#4:(返回Index,可以通过 tolist(), 或者 list(array) 转换为list)
data.columns
原文地址:https://blog.csdn.net/TH_NUM/article/details/80296254
查看pandas中的索引数据类型:
#少量数据:
import pandas as pd
data=pd.read_csv('./data/chipotle.tsv', sep='\t')
data.dtype
#大量数据:
import pandas as pd
data=pd.read_csv('./data/chipotle.tsv', sep='\t')
data_type=data.cloumns
for a in data_type:
print(a+':'+str(data[a].dtype))
pandas按照指定列排序:
import pandas as pd
data=pd.read_csv('./data/chipotle.tsv', sep='\t')
df = data.groupby(by=['item_name']).sum()
df.sort_values(by="item_name" , ascending=False)
#by: 指定列 ascending,False为降序,True为升序
pandas获取n行到m行
import pandas as pd
data=pd.read_csv('./data/chipotle.tsv', sep='\t')
data.local[n,m]#n,m为int
pandas获取指定列:
import pandas as pd
data=pd.read_csv('./data/chipotle.tsv', sep='\t')
#获取quantity和item_price列
data[['quantity','item_price']]
pandas指定列相乘:
import pandas as pd
data=pd.read_csv('./data/chipotle.tsv', sep='\t')
#获取quantity和item_price列
data[['quantity','item_price']]
data['col3']=data.apply(lambda data:data['quantity']*data['item_price'], axis=1)
#新建的col3列为指定列乘积
#若其中一项为string,则相乘只是将字符串重复
pandas中删除包含指定字符的行:
import pandas as pd
import numpy as np
data=pd.read_csv('./data/chipotle.tsv', sep='\t')
data=data[['quantity','item_price']]#单独显示价格和数量
#~必须有
data=data[~data['item_price'].str.contains('$')]
data
输出:
pandas中想取到包含某些字符的行:
import pandas as pd
import numpy as np
data=pd.read_csv('./data/chipotle.tsv', sep='\t')
data=data[['quantity','item_price']]#单独显示价格和数量
#去掉~即可
data=data[data['item_price'].str.contains('$')]
data
pandas中去除开头的$:
import pandas as pd
import numpy as np
data=pd.read_csv('./data/chipotle.tsv', sep='\t')
data=data[['quantity','item_price']]#单独显示价格和数量
data['item_price'].str.strip('$')
标签:文件,sep,python,pd,import,tsv,操作,data,pandas 来源: https://blog.csdn.net/ice_stone_kai/article/details/104830233