pandas数据框的使用

灬君兮灬 2019-01-17 04:17:49
# DataFrame

import pandas
import numpy

# DataFrame构建
t1 = pandas.DataFrame(numpy.arange(12).reshape(3, 4), index=list("123"), columns=list("abcd")) # 数组

di = {"name": ["xiaoming", "xioahua"], "age": [23, 21], "tel": [10086, 10010]}
t2 = pandas.DataFrame(di) # 字典

li = [{"name": "xiaoming", "age": 23, "tel": 10086}, {"name": "xiaohua", "age": 21, "tel": 10010}]
t3 = pandas.DataFrame(li) # 列表嵌套字典

df = pandas.DataFrame({"a": range(7), "b": range(7, 0, -1), 'c': ['one', 'one', 'one', 'two', 'two', 'two', 'two'], 'd': list("hjklmno")}, columns=list("abcd"))

# 常用操作
print(t2.index) # 列索引
print(t2.columns) # 行索引
print(t2.values) # 数据
print(t2.dtypes) # 每列的数据类型
print(t2.shape) # 形状(2,3)
print(t2.ndim) # 维度(2)
print(t2.head(1)) # 显示前1行,默认5
print(t2.tail()) # 显示后n行
print(t2.info()) # 显示数据概述
print(t2.describe()) # 数据描述(数值型:最值、中位数、均值)

# 排序方法
s = t3.sort_values(by="age", ascending=True) # ascending:默认升序(True)
print(s.head(1))

# 索引 -- 数据获取
# 方括号写数据,表示取行
# 方括号写字符串,表示取列
print(t2[:5]) # 取前5行:0-4
print(t2["age"]) # 取age列
print(t2[:5]["tel"])
# df.loc:通过标签索引行数据
print(t3.loc[0, "age"]) # 行标签:0,列标签:age
print(t3.loc[0, ]) # 一行或一列
print(t3.loc[[0, 1], ]) # 多行或多列
print(t3.loc[[0, 1], ["age", "tel"]])
# df.iloc:通过位置获取行标签
print(t3.iloc[0, :]) # 一行或一列
print(t3.iloc[0, 1])
print(t3.iloc[0:2, 1:3]) # 多行或多列 (0-1,1-2)
print(t3.iloc[[0, 1], [1, 2]])
# 布尔索引
print(t3[t3["age"] > 22])
print(t3[(t3["age"] > 22) & (t3["age"] < 25)]) # 多个条件()&()
print(t3[(t3["age"] > 22) | (t3["age"] < 25)])
# 字符串处理.str.cat()/contains()/count()/endswith/startswith/findall/get/join/len/lower/upper/match/pad/center/repeat/slice/split/strip/rstrip/lstrip
t3[t3["name"].str.len() > 2] # 名字(name列)字符串长度大于4


# 删除特征
df.drop(["time"], axis=1) #删除time字段,按列删除


# 缺失数据处理 -- nan不参与运算
t3.iloc[0, 0] = numpy.nan
pandas.isnull(t3) # 判断是否存在nan
pandas.notnull(t3) # 判断是否不为nan
t3[pandas.notnull(t3["name"])] # 选择name列不为nan的行
t3.dropna(axis=0, how="all", inplace=True) # axis:0行1列,how:all(全为nan才删),any(有一个就删),inplace是否修改原数据(默认false)
t3 = t3.fillna(t3.mean()) # 填充缺失值
t3["age"] = t3["age"].fillna(t3["age"].mean()) # 填充某一列缺失值


# 常用统计方法
t3["age"].mean() # 均值
t3["age"].max() # 最大值
t3["age"].argmax() # 最大值位置
t3["age"].min() # 最小值
t3["age"].argmin() # 最小值位置
t3["age"].median() # 中值
# 去重统计
len(set(t3["name"].tolist())) # 把名字变为列表取长度,人数
df["name"].unique() # 生成名字唯一的列表
len(df["name"].unique()) # 人数
# 获取演员人数 -- 字段中逗号分隔
ac_list = t3["name"].str.split(",").tolist() # 取演员列,以逗号切割,变为列表(大列表嵌套小列表)
a_list = [i for j in ac_list for i in j] # 列表展开
print(len(set(a_list)))


# 转置
df_T = df.T
...全文
44 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

37,721

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧