栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

pandas loc

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

pandas loc

df = pd.DataFrame([[1, 2], [4, 5], [7, 8]],
                  index=['cobra', 'viper', 'sidewinder'],
                  columns=['max_speed', 'shield'])
print(df)
print('-'*50)
print(df.loc['viper'])  # 返回的为serial
print(df.loc[['viper']])  # 返回的为DateFrame
print(df.loc['cobra', 'shield'])  # 返回的是一个label
print(df.loc['cobra':'viper', 'max_speed'])  # 按索引切片
print(df.loc[[False, False, True]])  # 与row相同的boolean 列表
print(df.loc[pd.Series([False, True, False],
                       index=['viper', 'sidewinder', 'cobra'])])

print(df.loc[pd.Index(["cobra", "viper"], name="foo")])  # 重置索引

print(df[df['shield'] > 6])  # print(df.loc[df['shield'] > 6]) 这俩的结果相等

print(df.loc[df['shield'] > 2,['max_speed']])
df.loc[['viper', 'sidewinder'], ['shield']] = 50 # 设置一个label的值
df.loc['cobra'] = 10 # 设置一行的值
df.loc[:,'max_speed'] = 30 # 设置一列的值
df.max_speed = 30 # 设置一列的值 根据column的值
df.loc[df['shield'] > 35] = 0 # df[df['shield'] > 35] = 0 根据条件设置行的值

# print(df)
tuples = [
   ('cobra', 'mark i'), ('cobra', 'mark ii'),
   ('sidewinder', 'mark i'), ('sidewinder', 'mark ii'),
   ('viper', 'mark ii'), ('viper', '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=['max_speed', 'shield'], index=index)
print(df)
print(df.loc['cobra'])
print(df.loc[('cobra', 'mark ii')])
print(df.loc[[('cobra', 'mark ii')]])
print(df.loc[('cobra', 'mark i'):'sidewinder'])
print(df.loc[('cobra', 'mark i'):('viper', 'mark ii')])

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/916092.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号