loc允许的输入为: 单个标签,例如5 or 'a'(请注意,它5被解释为索引的标签,而不是沿着索引的整数位置)。 标签列表或数组,例如.['a', 'b', 'c'] 带有标签的切片对象,例如'a':'f'。 需要注意的是违背了普通的Python片,开始和停止都包括 与被切片的轴长度相同的布尔数组,例如.[True, False, True] 一个可对齐的布尔系列。键的索引将在屏蔽之前对齐。 一个可对齐的索引。返回选择的索引将作为输入。 1、取值 import pandas as pddf = pd.DataFrame([[1, 2], [4, 5], [7, 8]], index=['cobra', 'viper', 'sidewinder'], columns=['max_speed', 'shield'])print(df)# max_speed shield#cobra 1 2#viper 4 5#sidewinder 7 8print(df.loc['viper']) #这一行将会作为一个Series返回#max_speed 4#shield 5#Name: viper, dtype: int64print(df.loc[['viper', 'sidewinder']]) #使用[[]]会返回一个DataFrame#其实形式为loc[[ , ], []] 第二个中括号没有内容被省略# max_speed shield#viper 4 5#sidewinder 7 8print(df.loc['cobra', 'shield']) #一个中括号内两个参数,行索引,列索引#2print(df.loc['cobra':'viper', 'max_speed']) #在切片时,首尾都包括#略#还可以通过与索引值长度相等的布尔列表完成print(df.loc[[False, False, True]])#通过pd.Index也可以索引取值print(df.loc[pd.Index(['cobra', 'viper'])]) 2.设置值
|
|