Pandas笔记:基本操作(读取,删除,索引,赋值,组合,排序)
import pandas as pd print("--------------------读取csv文件并显示前三行--------------------") data = pd.read_csv("./data/test.csv") print(data.head(3)) print("--------------------删除c,d列--------------------") data_drop = data.drop(["c", "d"], axis=1) print(data_drop.head(3)) print("--------------------索引--------------------") print(data["a"][1]) # a列第一个元素 print(data.loc[1:3, "c"]) # c列1到3行 print(data.iloc[0:2, 0:3]) # 0到2列,0到1行 print(data.loc[data.index[0:2], ["a"]]) # 组合索引:a列0,0到1行 print("--------------------赋值操作--------------------") data["a"] = 0 # a列全设置0 print(data.head(3)) print("--------------------排序操作--------------------") data_sort = data.sort_values(by="c", ascending=False) # 按c列按照数值大小排序False print(data.head(), "\n") print(data["a"].sort_index().head(3)) # 只有a列按照索引排序
运行结果:
--------------------读取csv文件并显示前三行-------------------- a b c d 0 1 2 3.0 4.0 1 1 2 NaN 4.0 2 1 ? 3.0 4.0 --------------------删除c,d列-------------------- a b 0 1 2 1 1 2 2 1 ? --------------------索引-------------------- 1 1 NaN 2 3.0 3 3.0 Name: c, dtype: float64 a b c 0 1 2 3.0 1 1 2 NaN a 0 1 1 1 --------------------赋值操作-------------------- a b c d 0 0 2 3.0 4.0 1 0 2 NaN 4.0 2 0 ? 3.0 4.0 --------------------排序操作-------------------- a b c d 0 0 2 3.0 4.0 1 0 2 NaN 4.0 2 0 ? 3.0 4.0 3 0 2 3.0 4.0 4 0 2 3.0 NaN 0 0 1 0 2 0 Name: a, dtype: int64