Pandas.DataFrame.loc函数用法大全

Pandas.DataFrame.loc

loc允许的输入为:

  • 单个标签,例如5 or 'a'(请注意,它5被解释为索引的标签,而不是沿着索引的整数位置)。
  • 标签列表或数组,例如.['a', 'b', 'c']
  • 带有标签的切片对象,例如'a':'f'需要注意的是违背了普通的Python片,开始和停止都包括
  • 与被切片的轴长度相同的布尔数组,例如.[True, False, True]
  • 一个可对齐的布尔系列。键的索引将在屏蔽之前对齐。
  • 一个可对齐的索引。返回选择的索引将作为输入。

1.获取值

import pandas as pd

df = 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       8

print(df.loc['viper'])  #这一行将会作为一个Series返回
#max_speed    4
#shield       5
#Name: viper, dtype: int64

print(df.loc[['viper', 'sidewinder']])  #使用[[]]会返回一个DataFrame
#其实形式为loc[[ , ], []] 第二个中括号没有内容被省略
#            max_speed  shield
#viper               4       5
#sidewinder          7       8

print(df.loc['cobra', 'shield'])  #一个中括号内两个参数,行索引,列索引
#2

print(df.loc['cobra':'viper', 'max_speed'])  #在切片时,首尾都包括
#略
#还可以通过与索引值长度相等的布尔列表完成
print(df.loc[[False, False, True]])

#通过pd.Index也可以索引取值
print(df.loc[pd.Index(["cobra", "viper"])])

2.设置值

#将行索引为viper和sidewinder列索引为shield的元素设定为50
df.loc[['viper', 'sidewinder'], ['shield']] = 50
print(df)
#            max_speed  shield
#cobra               1       2
#viper               4      50
#sidewinder          7      50

#为整行设置值,只设置索引就可以修改一整行内容
df.loc['cobra'] = 10
print(df)
#            max_speed  shield
#cobra              10      10
#viper               4      50
#sidewinder          7      50

#为整列设置值, 行索引设置为:表示所有行
df.loc[:, 'max_speed'] = 30
#略

#为匹配可调用条件的行设置值
df.loc[df['shield'] > 35] = 0
print(df)
#            max_speed  shield
#cobra              30      10
#viper               0       0
#sidewinder          0       0

猜你喜欢

转载自blog.csdn.net/gary101818/article/details/122454196