“Pandas”的版本间差异

来自Shiyin's note
跳到导航 跳到搜索
→‎io
第44行: 第44行:
file=pd.read_table(path+'test1.spectrum',skiprows=range(0,6),\
file=pd.read_table(path+'test1.spectrum',skiprows=range(0,6),\
delim_whitespace=True, names=('A', 'B', 'C'), dtype={'A': np.int64, 'B': np.float64, 'C': np.float64})
delim_whitespace=True, names=('A', 'B', 'C'), dtype={'A': np.int64, 'B': np.float64, 'C': np.float64})
a=file['A'].values
*sep='\s+'(分隔符号是空格)


==hdf5==
==hdf5==

2021年6月24日 (四) 12:45的版本

Python Data Analysis Library

数据结构

DataFrame

df = pd.DataFrame([[1, 2, 3],[4, 5, 6]], columns=['col1','col2','col3'], index=['a','b'])
  • 表格方式定义,行是 index, 列是columns,值是values
df.index 
df.columns
df.values  #二维数组
  • 调用行 df.loc(['a']),调用列 df['col1']
  • df[0:1]调用第一行,df[0]调用第一列

Series

  • 每一项称为items,比较像字典,又分为index和values
  • 默认的index是range(),所以可以从ndarray转换而来
  • 可以从字典装换而来,key是变成index
sdata = {'Ohio': 35000, 'Texas': 71000, 'Oregon': 16000, 'Utah': 5000}
ser3 = Series(sdata)
  • 不同Series对象可以根据索引进行匹配计算。
  • 根据索引进行检索:ser3.loc['Ohio']
  • Series.describe() #看这个序列数值的基本统计量
  • 缺失值处理 Series.isnull(), Series.notnull(), Series.fillnull()

Index

  • 比较像集合set,但是元素可以重复

io

  • read_csv
import pandas as pd
data=pd.read_csv('cGs_for_LAMOST.csv',comment='#')
data.columns
ra=data['ra']
dec=data['dec]
comment='#'
sep=' '(或者'\s' ;sep='\t'(分隔符是Tab键)
  • read_table

:读普通的ascii文件

file=pd.read_table(path+'test1.spectrum',skiprows=range(0,6),\
                 delim_whitespace=True, names=('A', 'B', 'C'), dtype={'A': np.int64, 'B': np.float64, 'C': np.float64})
a=file['A'].values
  • sep='\s+'(分隔符号是空格)

hdf5

  • 复杂数据结构可以组合成一个hdf5结构 [1]
  • 写入
store = pd.HDFStore('store.h5')
#生成一个1亿行,5列的标准正态分布随机数表
df = pd.DataFrame(np.random.rand(100000000,5))
store['df'] = df
####压缩格式存储
h5 = pd.HDFStore('store_comp.h5','w', complevel=4, complib='blosc')
h5['data'] = df
  • 读入
store = pd.HDFStore('Omet_CEM.h5')
store.keys()

pickle

  • 使用DataFrame的to_pickle属性就可以生成pickle文件对数据进行永久储存
df = pd.DataFrame(np.arange(20).reshape(4,5))
df.to_pickle('foo.pkl')
pd.read_pickle('foo.pkl')