One - One Code All

Blog Content

python中pandas的dataframe对象的创建及矩阵模拟赋值

Python 统计学-科学计算   2015-10-02 22:47:04

DataFrame对象的创建,修改,合并

import pandas as pd
import numpy as np

# 创建DataFrame对象
df = pd.DataFrame([1, 2, 3, 4, 5], columns=['cols'], index=['a','b','c','d','e'])
df2 = pd.DataFrame([[1, 2, 3],[4, 5, 6]], columns=['col1','col2','col3'], index=['a','b'])
df3 = pd.DataFrame(np.array([[1,2],[3,4]]), columns=['col1','col2'], index=['a','b'])
df4 = pd.DataFrame({'col1':[1,3],'col2':[2,4]},index=['a','b'])

# 模拟矩阵,创建维度为5的空矩阵
list_col = range(0,6)
df5 = pd.DataFrame(columns=list_col, index=list_col)
# 矩阵赋值 [列,行] df5.iat[i,j] = n
df5.iat[0,1] = 1

创建DataFrame对象的数据可以为列表,数组和字典,列名和索引为列表对象

基本操作
# 根据索引查看数据
df2.loc['a']   
# 索引为a这一行的数据
# df2.iloc[0] 跟上面的操作等价,一个是根据索引名,一个是根据数字索引访问数据

print(df2.loc[['a','b']])   # 访问多行数据,索引参数为一个列表对象

# 访问列数据
print(df2[['col1','col3']])

计算

# DataFrame元素求和
# 默认是对每列元素求和
df2.sum()

# 行求和
df2.sum(1)

# 对每个元素乘以2
df2.apply(lambda x:x*2)

# 对每个元素求平方(支持ndarray一样的向量化操作)
df2**2

列扩充

# 对DataFrame对象进行列扩充
df2['col4'] = ['cnn','rnn']

# 也可以通过一个新的DataFrame对象来定义一个新列,索引自动对应
df2['col5'] = pd.DataFrame(['MachineLearning','DeepLearning'],index=['a','b'])

行扩充

# 行进行扩充
df2.append(pd.DataFrame({'col1':7,'col2':8,'col3':9,'col4':'rcnn','col5':'ReinforcementLearning'},index=['c']))12

注意!

# 如果在进行 行扩充时候没有,指定index的参数,索引会被数字取代
df2.append({'col1':10,'col2':11,'col3':12,'col4':'frnn','col5':'DRL'},ignore_index=True)

# 以上的行扩充,并没有真正修改,df2这个DataFrame对象,除非
df2 = df2.append(pd.DataFrame({'col1':7,'col2':8,'col3':9,'col4':'rcnn','col5':'ReinforcementLearning'},index=['c']))

DataFrame对象的合并

# DataFrame 对象的合并
df_a = pd.DataFrame(['wang','jing','hui','is','a','master'],columns=['col6'],index=['a','b','c','d','e','f'])

# 默认合并,只保留dfb中的全部索引
dfb = pd.DataFrame([1,2,4,5,6,7],columns=['col1'],index=['a','b','c','d','f','g'])
dfb.join(df_a)

# 默认合并之接受索引已经存在的值
# 通过指定参数 how,指定合并的方式
dfb.join(df_a,how='inner')   # 合并两个DataFrame对象的交集

# 合并两个DataFrame对象的并集
dfb.join(df_a,how='outer')


上一篇:padas的dataframe获取某行某列单个值loc与iloc
下一篇:pandas计算工具汇总pct_change协方差

The minute you think of giving up, think of the reason why you held on so long.