import pandas as pd
import numpy as np
df = pd.DataFrame(np.arange(24).reshape(6,4),index=list("ABCDEF"),columns=list("WXYZ"))
# df 输出的结果为:
W X Y Z
A 0 1 2 3
B 4 5 6 7
C 8 9 10 11
D 12 13 14 15
E 16 17 18 19
F 20 21 22 23
# df_sorted = df.sort_values(by="列名")
df_sorted = df.sort_values(by="Z")[:3] 按Z列排序,并取前三行
# 输出结果为:
W X Y Z
A 0 1 2 3
B 4 5 6 7
C 8 9 10 11
df.loc["D"] # loc取单行
# 输出结果为:
W 12
X 13
Y 14
Z 15
Name: D, dtype: int32
df.loc["A":"D"] # loc取连续多行
# 输出结果为:
W X Y Z
A 0 1 2 3
B 4 5 6 7
C 8 9 10 11
D 12 13 14 15
df.loc[["A","D"]] # loc取不连续多行
# 输出结果为:
W X Y Z
A 0 1 2 3
D 12 13 14 15
df.iloc[0] # iloc取单行
# 输出结果为:
W 0
X 1
Y 2
Z 3
Name: A, dtype: int32
df.iloc[1:3] # iloc取连续多行
# 输出结果为:
W X Y Z
B 4 5 6 7
C 8 9 10 11
df.iloc[[0,2,3]] # iloc取不连续多行
# 输出结果为:
W X Y Z
A 0 1 2 3
C 8 9 10 11
D 12 13 14 15
df.loc[:,"Y"]
# 输出结果为: # loc取单列
A 2
B 6
C 10
D 14
E 18
F 22
Name: Y, dtype: int32
df.loc[:,"X":"Z"]
# 输出结果为: # loc取连续多列
X Y Z
A 1 2 3
B 5 6 7
C 9 10 11
D 13 14 15
E 17 18 19
F 21 22 23
df.loc[:,["X","Z"]] # loc取不连续多列
# 输出结果为:
X Z
A 1 3
B 5 7
C 9 11
D 13 15
E 17 19
F 21 23
df.iloc[:,2] # iloc取单列
# 输出结果为:
A 2
B 6
C 10
D 14
E 18
F 22
Name: Y, dtype: int32
df.iloc[:,1:3] # iloc取连续多列
# 输出结果为:
X Y
A 1 2
B 5 6
C 9 10
D 13 14
E 17 18
F 21 22
df.iloc[:,[0,2]] # iloc取不连续多列
# 输出结果为:
W Y
A 0 2
B 4 6
C 8 10
D 12 14
E 16 18
F 20 22
df.loc["C","Y"] # loc取单行单列,即为某一个坐标的值
# 输出结果为:
10
df.loc["A":"C","X":"Z"] # loc取连续多行多列
# 输出结果为:
X Y Z
A 1 2 3
B 5 6 7
C 9 10 11
df.loc[["A","C","E"],["W","Y"]] # loc取不连续多行多列
# 输出结果为:
W Y
A 0 2
C 8 10
E 16 18
df.iloc[2,2] # iloc取单行单列,即为某一个坐标的值
# 输出结果为:
10
df.iloc[0:3,1:4] # iloc取连续多行多列
# 输出结果为:
X Y Z
A 1 2 3
B 5 6 7
C 9 10 11
df.iloc[[0,2,4],[0,2]] # iloc取不连续多行多列
# 输出结果为:
W Y
A 0 2
C 8 10
E 16 18
df.iloc[[0,2,4],[0,2]] = np.nan
# df输出结果为:
W X Y Z
A NaN 1 NaN 3
B 4.0 5 6.0 7
C NaN 9 NaN 11
D 12.0 13 14.0 15
E NaN 17 NaN 19
F 20.0 21 22.0 23
df[(df["Z"]>10)&(df["Z"]<20)]
# 输出结果为:
W X Y Z
C NaN 9 NaN 11
D 12.0 13 14.0 15
E NaN 17 NaN 19