總結一下 DataFrame索引問題
1.索引是什么
1.1 認識索引
先創(chuàng)建一個簡單的DataFrame。
myList = [['a', 10, 1.1],
['b', 20, 2.2],
['c', 30, 3.3],
['d', 40, 4.4]]
df1 = pd.DataFrame(data = myList)
print(df1)
--------------------------------
[out]:
0 1 2
0 a 10 1.1
1 b 20 2.2
2 c 30 3.3
3 d 40 4.4
DataFrame中有兩種索引:
- 行索引(index):對應最左邊那一豎列
- 列索引(columns):對應最上面那一橫行
兩種索引默認均為從0開始的自增整數(shù)。
# 輸出行索引
print(df1.index)
[out]:
RangeIndex(start=0, stop=4, step=1)
---------------------------------------
# 輸出列索引
print(df1.columns)
[out]:
RangeIndex(start=0, stop=3, step=1)
---------------------------------------
# 輸出所有的值
print(df1.values)
[out]:
array([['a', 10, 1.1],
['b', 20, 2.2],
['c', 30, 3.3],
['d', 40, 4.4]], dtype=object)
1.2 自定義索引
可以使用 index 這個參數(shù)指定行索引,columns 這個參數(shù)指定列索引。
df2 = pd.DataFrame(myList,
index = ['one', 'two', 'three', 'four'],
columns = ['char', 'int', 'float'])
print(df2)
-----------------------------------------------------------
[out]:
char int float
one a 10 1.1
two b 20 2.2
three c 30 3.3
four d 40 4.4
輸出此時的行索引和列索引:
# 輸出行索引
print(df2.index)
[out]:
Index(['one', 'two', 'three', 'four'], dtype='object')
--------------------------------------------------------
# 輸出列索引
print(df2.columns)
[out]:
Index(['char', 'int', 'float'], dtype='object')
2. 索引的簡單使用
2.1 列索引
- 選擇一列:
print(df2['char'])
print(df2.char)
# 兩種方式輸出一樣
[out]:
one a
two b
three c
four d
Name: char, dtype: object
注意此時方括號里面只傳入一個字符串 ’char’,這樣選出來的一列,結果的類型為 Series
type(df2['char'])
[out]: pandas.core.series.Series
- 選擇多列:
print(df2[['char', 'int']])
[out]:
char int
one a 10
two b 20
three c 30
four d 40
注意此時方括號里面?zhèn)魅胍粋€列表 [‘char’, ‘int’],選出的結果類型為 DataFrame。
如果只想選出來一列,卻想返回 DataFrame 類型怎么辦?
print(df2[['char']])
[out]:
char
one a
two b
three c
four d
---------------------------------------
type(df2[['char']])
[out]:pandas.core.frame.DataFrame
注意直接使用 df2[0] 取某一列會報錯,除非columns是由下標索引組成的,比如df1那個樣子,df1[0] 就不會報錯。
print(df1[0])
[out]:
0 a
1 b
2 c
3 d
Name: 0, dtype: object
-----------------------
print(df2[0])
[out]:
KeyError: 0
2.1.2 使用loc和iloc
df = dat_df.iloc[:, [0, 2, 3, 4]] #選擇所有行,并選擇第0,2,3,4列,列名可以為其它字符串
2.2 行索引
2.2.1 使用[ : ]
區(qū)別于選取列,此種方式 [ ] 中不再單獨的傳入一個字符串,而是需要使用冒號切片。
- 選取行標簽從 ’two’ 到 ’three’ 的多行數(shù)據(jù)
print(df2['two': 'three'])
[out]:
char int float
two b 20 2.2
three c 30 3.3
# dataframe格式
# 也可以直接用數(shù)字
- 選取行標簽為 ’two’ 這一行數(shù)據(jù)
# 此時返回的類型為DataFrame
print(df2['two': 'two'])
[out]:
char int float
two b 20 2.2
在 [ ] 中不僅可以傳入行標簽,還可以傳入行的編號。
- 選取從第1行到第3行的數(shù)據(jù)(編號從0開始)
print(df2[1:4])
[out]:
char int float
two b 20 2.2
three c 30 3.3
four d 40 4.4
# dataframe格式
可以看到選取的數(shù)據(jù)是不包含方括號最右側的編號所對應的數(shù)據(jù)的。
- 選取第1行的數(shù)據(jù)
print(df2[1:2])
[out]:
char int float
two b 20 2.2
2.2.2 使用.loc()和.iloc()
區(qū)別就是 .loc() 是根據(jù)行索引和列索引的值來選取數(shù)據(jù),而 .iloc() 是根據(jù)從 0 開始的下標位置來進行索引的。
- 選取行:
1. 使用.loc()
print(df2.loc['one'])
[out]:
char a
int 10
float 1.1
Name: one, dtype: object
-------------------------------------------
print(df2.loc[['one', 'three']])
[out]:
char int float
one a 10 1.1
three c 30 3.3
-------------------------------------------
df2.loc['one': 'three']
Out[14]:
char int float
one a 10 1.1
two b 20 2.2
three c 30 3.3
2. 使用.iloc()
print(df2.iloc[0])
[out]:
char a
int 10
float 1.1
Name: one, dtype: object
-------------------------------------------
print(df2.iloc[[0, 2]])
[out]:
char int float
one a 10 1.1
three c 30 3.3
-------------------------------------------
df2.iloc[1: 3]
Out[18]:
char int float
two b 20 2.2
three c 30 3.3
3. 根據(jù)列條件,選取dataframe數(shù)據(jù)框中的數(shù)據(jù)
# 選取等于某些值的行記錄 用 ==
df.loc[df['column_name'] == some_value]
# 選取某列是否是某一類型的數(shù)值 用 isin
df.loc[df['column_name'].isin(some_values)]
# 多種條件的選取 用 &
df.loc[(df['column'] == some_value) & df['other_column'].isin(some_values)]
# 選取不等于某些值的行記錄 用 !=
df.loc[df['column_name'] != some_value]
# isin返回一系列的數(shù)值,如果要選擇不符合這個條件的數(shù)值使用~
df.loc[~df['column_name'].isin(some_values)]
4. 根據(jù)列條件,獲取行索引號并轉成列表
在dataframe中根據(jù)一定的條件,得到符合要求的某些行元素所在的位置
import pandas as pd
df = pd.DataFrame({'BoolCol': [1, 2, 3, 3, 4],'attr': [22, 33, 22, 44, 66]},
index=[10,20,30,40,50])
print(df)
a = df[(df.BoolCol==3)&(df.attr==22)].index.tolist()
print(a)
輸出:
BoolCol attr
10 1 22
20 2 33
30 3 22
40 3 44
50 4 66
[30]
注意:df[(df.BoolCol==3)&(df.attr==22)].index 返回的是 index 對象列表,需轉換為普通列表格式時用 tolist() 方法
文章來源:http://www.zghlxwxcb.cn/news/detail-402309.html
5. 索引操作集錦
a = data_1H2['num'].value_counts(sort=True, ascending=True).sort_index(ascending=False)
參考鏈接
[1] Pandas中DataFrame索引、選取數(shù)據(jù) 2020.3文章來源地址http://www.zghlxwxcb.cn/news/detail-402309.html
到了這里,關于python中Pandas之DataFrame索引、選取數(shù)據(jù)的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!