dateframe 基本操作和运算

# hanbb
# come on!!!
import pandas as pd
import numpy as np
df = pd.DataFrame(np.arange(12).reshape(4,3),index=['a','b','c','d'],columns=['1st','2nd','3rd'])
print(df)
# 取值
print(df.values)
print(df.index)
print(df.columns)

print(df['1st'])          # 取出列数据,
print(df.ix['a'])         # 取出行数据
print(df['3rd']['d'])     # 取出一个数据

# 改变索引,重新索引
df.reindex(columns=['3rd','2nd','1st'])
print(df)
# 新增
#
newc = df.columns.insert(4,'4or')             # 增加新的一列 指定列索引,指定自定义索引
newd = df.reindex(columns=newc,fill_value=20) # 填充固定值
print(newd)
#
newi = df.index.insert(5,'e')
newd1= df.reindex(index=newi,fill_value=30)
print(newd1)

# 删除
newc2= df.columns.delete(2)                # 核心是基于行列索引来操作数据
newd3= df.reindex(columns=newc2)
print(newd3)

# drop 直接删除 行和列
print(df.drop('c'))          # 默认是行
print(df.drop('2nd',axis=1)) # 改为1,即为列

更新行列数据的提取:

import pandas as pd

# 数据的导入
data = pd.read_table("E:\\python\\part 2\\017\\TRD_Index.txt",sep='\t')  # 注意分隔符
print(data.tail())

# 获取 行标签 相同的数据
sh_data=data[data.Indexcd==1]
print(sh_data["Retindex"].tail())    # 这两个格式效果一致的
print(sh_data.Retindex.tail())
# 多列
sh_data_2=data[data['Indexcd']<=2] # 取出列标签 Indexcd 小于等于2的数据
# 获取列数据
print(data["Indexcd"].tail())        # 这两个格式效果一致的
print(data.Indexcd.tail())
# 获取两列数据
print(data[['Indexcd','Trddt']]) # 注意符号

 

 2.基本运算

import pandas as pd
import numpy as np
df1 = pd.DataFrame(np.arange(12).reshape(4,3),index=['a','b','c','d'],columns=['1st','2nd','3rd'])
df2 = pd.DataFrame(np.arange(16).reshape(4,4),index=['a','b','c','d'],columns=['1st','2nd','3rd','4or'])

# 直接符号运算
print(df1+df2)
print(df1-df2)
print(df1*df2)

# 可以填充值的加减乘除
print(df1.add(df2,fill_value=20))
print(df1.sub(df2,fill_value=20))
print(df1.mul(df2,fill_value=20))
print(df1.div(df2,fill_value=20))

# 比较运算,必须是相同维度的比较
print(df2['1st']>df1['1st'])

 

posted @ 2017-11-19 16:39  hbb360  阅读(1122)  评论(0编辑  收藏  举报