本文共 4214 字,大约阅读时间需要 14 分钟。
DataFrame是pandas中核心的数据结构,它类似于Excel中的表格,支持多种数据类型(数值、字符串、布尔型等),并具有行索引和列索引。行索引称为index(默认从0开始),列索引称为columns(同样默认从0开始)。
通过二维数组创建
最常用的方式是使用numpy数组创建DataFrame:import pandas as pdimport numpy as npt1 = pd.DataFrame(np.arange(12).reshape((3,4)))print(t1)
输出结果:
0 1 2 30 0 1 2 31 4 5 6 72 8 9 10 11
通过字典创建
DataFrame也可以通过字典来创建,但需要注意字典中的值必须是一维数组或单个数据类型:d2 = { "name": ["张三", "李四", "王五"], "age": ["20", "21", "20"], "tel": ["10086", "10010", "35699"]}t2 = pd.DataFrame(d2)print(t2)输出结果:
name age tel0 张三 20 100861 李四 21 100102 王五 20 35699
通过字典中的数组创建
如果字典中的值是数组,需确保所有数组长度一致:d3 = [ {"name": "张三", "age": "20", "tel": "10086"}, {"name": "李四", "tel": "10010"}, {"age": "20", "tel": "35699"}]t3 = pd.DataFrame(d3)print(t3)输出结果:
name age tel0 张三 20 100861 李四 NaN 100102 NaN 20 35699
DataFrame的行索引和列索引默认从0开始,可以通过index和columns属性进行设置:
t1 = pd.DataFrame(np.arange(12).reshape((3,4)), index=["a", "b", "c"], columns=["W", "X", "Y", "Z"])print(t1)
输出结果:
W X Y Za 0 1 2 3b 4 5 6 7c 8 9 10 11
索引和列
print(t2.index) # RangeIndex(3)print(t2.columns) # Index(['name', 'age', 'tel'], dtype='object')
数据值
print(t2.values)
输出结果:
[['张三' '20' '10086']['李四' '21' '10010']['王五' '20' '35699']]
维度和形状
print(t2.ndim) # 2print(t2.shape) # (3, 3)
数据类型
print(t2.dtypes)
输出结果:
name objectage objecttel objectdtype: object
查看前几行和后几行
print(t2.head(2)) # 显示前两行print(t2.tail(2)) # 显示后两行
数据信息
print(t2.info()) # 展示DataFrame的具体信息
输出结果:
RangeIndex: 3 entries, 0 to 2 Data columns (total 3 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 name 3 non-null object 1 age 3 non-null object 2 tel 3 non-null object dtypes: object(3) memory usage: 200.0+ bytes
描述性统计
print(t2.describe())
输出结果:
name age telcount 3 3 3unique 3 2 3top 王五 20 10086freq 1 2 1
可以通过sort_values方法对DataFrame进行排序:
t2 = t2.sort_values(by="age") # 升序排列print(t2)
输出结果:
name age tel0 张三 20 100862 王五 20 356991 李四 21 10010
降序排列:
t2 = t2.sort_values(by="age", ascending=False)print(t2)
输出结果:
name age tel1 李四 21 100100 张三 20 100862 王五 20 35699
行和列的切片操作
print(t3[:2]) # 取行索引为0和1的数据print(t3[2:]) # 取行索引为2到末尾的数据
单列或多列切片
print(t3["age"]) # 取出age列print(type(t3["age"])) # 返回Series对象print(t3[:2]["age"]) # 取出前两行的age列
字典访问方式
order_id = detail1["order_id"]print(order_id.shape) # (2779,)dishes_names = detail1.dishes_nameprint(dishes_names.shape) # (2779,)
new_row = {"order_id": "458", "dishes_name": "蒜香辣花甲"}updated_df = detail1.append(new_row)print("新增后的数据形状:", updated_df.shape) # 删除某一行detail1 = detail1.drop(3, inplace=True)print("删除后的数据形状:", detail1.shape)# 删除某几列detail1 = detail1.drop(["order_id", "dishes_name"], inplace=True)print("删除后的数据形状:", detail1.shape) # 修改某一行的数据detail1.loc[0] = {"order_id": "458", "dishes_name": "蒜香辣花甲"}print("修改后的第一行数据:", detail1.iloc[0])# 修改多行数据detail1.iloc[1:3] = [["458", "蒜香辣花甲"], ["459", "剁椒鱼头"]]print("修改后的数据形状:", detail1.shape) DataFrame的查询可以结合切片操作完成,例如:
# 根据order_id筛选出特定订单的信息detail1[detail1["order_id"] == "458"]# 结合多个条件查询detail1[(detail1["order_id"] == "458") & (detail1["dishes_name"].str.contains("辣"))] 数值型特征描述
使用describe()方法可以得到数值型数据的基本统计信息:print(detail1["counts"].describe()) # 查看counts列的描述性统计print(detail1[["counts", "amounts"]].describe()) # 查看多列的描述性统计
类别型特征描述
对于类别型特征,可以使用value_counts()方法进行频数统计:print(detail1["order_id"].value_counts()) # 查看order_id的频率分布
优化代码实现
def dropNullStd(data): before_len = data.shape[1] count_null = data.describe().loc['count'] == 0 for i in count_null.index: if count_null[i]: data.drop(i, axis=1, inplace=True) std_zero = data.describe().loc['std'] == 0 for i in std_zero.index: if std_zero[i]: data.drop(i, axis=1, inplace=True) after_len = data.shape[1] print(f"剔除列的数目:{before_len - after_len}") print(f"剔除后的数据形状:{data.shape}")dropNullStd(detail1)通过以上方法,可以对DataFrame进行基本操作和分析,掌握使用pandas进行数据分析的核心技能。
转载地址:http://behq.baihongyu.com/