''' @标题:常用帮助 @作者:汉江S @版本:v1.0 @时间:2021-1-8 ''' import pandas as pd #loc函数使用说明 df = pd.DataFrame([[1, 2], [4, 5], [7, 8]], index=['第一行', '第二行', '第二行'], columns=['第一列', '第二列']) print(df) ''' #一选择 df = pd.DataFrame([[1, 2], [4, 5], [7, 8]], index=['第一行', '第二行', '第二行'], columns=['第一列', '第二列']) print(df) #1单个 row_label 返回的Series df.loc['第二行'] print(df.loc['第二行']) #2列表 row_label 返回的DataFrame print(df.loc[['第一行','第二行']]) #3同时选定行和列,返回单元值 print(df.loc['第一行', '第二列']) #4同时选定多个行和单个列,注意的是通过列表选定多个row label 时,首位均是选定的。 print(df.loc['第一行':'第二行', '第一列']) #5布尔列表选择row label布尔值列表是根据某个位置的True or False 来选定,如果某个位置的布尔值是True,则选定该row print(df.loc[[True,False,True]]) #6返回条件布尔值 print(df.loc[df['第二列'] > 6]) #7条件布尔值和具体某列的数据 print(df.loc[df['第二列'] > 6, ['第一列']]) #8通过函数得到布尔结果选定数据 print(df.loc[lambda df: df['第二列'] == 8]) ''' ''' #二赋值 # 根据某列表选定的row 及某列 column 赋值 df.loc[['第二行', '第二行'], ['第二列']] = 50 print(df) #将某行row的数据全部赋值 df.loc['第一行'] =10 print(df) #将某列的数据完全赋值 df.loc[:, '第一列'] = 30 print(df) #条件选定rows赋值 df.loc[df['第二列'] > 35] = 0 print(df) ''' tuples = [ ('第一行', 'mark i'), ('第一行', 'mark ii'), ('第二行', 'mark i'), ('第二行', 'mark ii'), ('第二行', 'mark ii'), ('第二行', 'mark iii') ] index = pd.MultiIndex.from_tuples(tuples) values = [[12, 2], [0, 4], [10, 20], [1, 4], [7, 1], [16, 36]] df = pd.DataFrame(values, columns=['第一列', '第二列'], index=index) print(df) print(df.loc[('第一行', 'mark ii')]) print(df.loc['第一行', 'mark i']) print(df.loc[[('第一行', 'mark ii')]]) print(df.loc[('第一行', 'mark i'), '第二列']) print(df.loc[('第一行', 'mark i'):'第二行']) print(df.loc[('第一行', 'mark i'):'第二行']) print(df.loc[('第一行', 'mark i'):('第二行','mark i')])