网站建设加推广话术,kunkka wordpress,专业网站建设模板下载,东莞市阳光网1、DataFrame 索引
1.1 普通索引取值
pandas 取行或者列的注意点#xff1a;
方括号写数组#xff0c;表示取行#xff0c;对行进行操作方括号写字符串#xff0c;表示取列#xff0c;对列进行操作
import pandas as pd
import numpy as np
# pandas 取行或者列的注意…1、DataFrame 索引
1.1 普通索引取值
pandas 取行或者列的注意点
方括号写数组表示取行对行进行操作方括号写字符串表示取列对列进行操作
import pandas as pd
import numpy as np
# pandas 取行或者列的注意点
# 方括号写数组表示取行对行进行操作
# 方括号写字符串表示取列对列进行操作
t1 pd.DataFrame(np.arange(12).reshape(3,4), indexlist(abc), columnslist(wxyz))
print(t1)
w x y z
a 0 1 2 3
b 4 5 6 7
c 8 9 10 11print(t1[:2])
w x y z
a 0 1 2 3
b 4 5 6 7print(t1[:2][x])a 1
b 5
Name: x, dtype: int32print(t1[y])a 2
b 6
c 10
Name: y, dtype: int321.2 DataFrame.loc 通过标签索引行数据
取行
t3 pd.DataFrame(np.arange(12).reshape(3,4), indexlist(abc), columnslist(wxyz))
print(t3)
w x y z
a 0 1 2 3
b 4 5 6 7
c 8 9 10 11print(t3.loc[a, z]) # 3 a 行 z 列
print(type(t3.loc[a, z])) # class numpy.int32
# 取第 b 行
print(t3[1:2])
print(t3.loc[a])
print(t3.loc[a, :])
w x y z
b 4 5 6 7
w 0
x 1
y 2
z 3
Name: a, dtype: int32
w 0
x 1
y 2
z 3
Name: a, dtype: int32取列
# 取第 y 列
print(t3[y])
print(t3.loc[:,y])a 2
b 6
c 10
Name: y, dtype: int32
a 2
b 6
c 10
Name: y, dtype: int32取 多行 多列
print(t3.loc[[a,b], [w, z]])
w z
a 0 3
b 4 7print(t3.loc[a:c, [w, z]]) # 注意 c 行被选中了
w z
a 0 3
b 4 7
c 8 11print(t3.loc[[a,b]])
w x y z
a 0 1 2 3
b 4 5 6 7print(t3.loc[:, [w, z]])
w z
a 0 3
b 4 7
c 8 111.3 DataFrame.iloc 通过位置获取行数据
取行
print(t3)
w x y z
a 0 1 2 3
b 4 5 6 7
c 8 9 10 11print(t3.iloc[1]) # 取行w 4
x 5
y 6
z 7
Name: b, dtype: int32取列
print(t3.iloc[:, 1])a 1
b 5
c 9
Name: x, dtype: int32
# 取多列
print(t3.iloc[:, [2,1]])
y x
a 2 1
b 6 5
c 10 9取多行 多列
print(t3.iloc[[0,2], [2,1]])
y x
a 2 1
c 10 9print(t3.iloc[1:,:2])
w x
b 4 5
c 8 9t3.iloc[1:,:2] 30
print(t3)
w x y z
a 0 1 2 3
b 30 30 6 7
c 30 30 10 112、DataFrame bool索引
print(t3)
w x y z
a 0 1 2 3
b 30 30 6 7
c 30 30 10 11print(t3[t3[y] 3])
w x y z
b 30 30 6 7
c 30 30 10 11print(t3[(t3[y] 3) (t3[y]20)])
w x y z
b 30 30 6 7
c 30 30 10 11print(t3[(t3[y] 3) |(t3[y]20)])
w x y z
a 0 1 2 3
b 30 30 6 7
c 30 30 10 113、pandas 字符串方法 data [[Google,10],[Runoob,12],[Wiki,13]]
df pd.DataFrame(data,columns[Site,Age])
print(df)
Site Age
0 Google 10
1 Runoob 12
2 Wiki 13print(df[df[Site].str.len()4])
Site Age
0 Google 10
1 Runoob 12print(df[Site].str.split(o))0 [G, , gle]
1 [Run, , b]
2 [Wiki]
Name: Site, dtype: objectprint(df[Site].str.split(o).tolist())[[G, , gle], [Run, , b], [Wiki]]https://www.bilibili.com/video/BV1hx411d7jb?p27 https://www.bilibili.com/video/BV1hx411d7jb?p28 https://www.runoob.com/pandas/pandas-dataframe.html