Pandas 教程-Pandas DataFrame.loc[]
整理:python架构师
DataFrame.loc[] 用于通过标签或布尔数组在 DataFrame 中检索行和列的组。它只接受索引标签,如果它存在于调用者 DataFrame 中,它将返回行、列或 DataFrame。
DataFrame.loc[] 是基于标签的,但可以与布尔数组一起使用。
.loc[] 的允许输入包括:
单个标签,例如7或a。这里,7被解释为索引的标签。
标签的列表或数组,例如['x','y','z']。
带有标签的切片对象,例如'x':'f'。
相同长度的布尔数组,例如[True,True,False]。
具有一个参数的 callable 函数。
语法
pandas.DataFrame.loc[]
返回
它返回标量、Series 或 DataFrame。
示例
import pandas as pd# Creating the DataFrameinfo = pd.DataFrame({'Age':[32, 41, 44, 38, 33],'Name':['Phill', 'William', 'Terry', 'Smith', 'Parker']})# Create the indexindex_ = ['Row_1', 'Row_2', 'Row_3', 'Row_4', 'Row_5']# Set the indexinfo.index = index_# return the valuefinal = info.loc['Row_2', 'Name']# Print the resultprint(final)
William
专属福利 👉点击领取:最全Python资料合集
示例2:
# importing pandas as pdimport pandas as pd# Creating the DataFrameinfo = pd.DataFrame({"P":[28, 17, 14, 42, None],"Q":[15, 23, None, 15, 12],"R":[11, 23, 16, 32, 42],"S":[41, None, 34, 25, 18]})# Create the indexindex_ = ['A', 'B', 'C', 'D', 'E']# Set the indexinfo.index = index_# Print the DataFrameprint(info)
P Q R SA 28.0 15.0 11 41.0B 17.0 23.0 23 NaNC 14.0 NaN 16 34.0D 42.0 15.0 32 25.0E NaN 12.0 42 18.0
# return the valuesresult = info.loc[:, ['P', 'S']]# Print the resultprint(result)
P SA 28.0 41.0B 17.0 NaNC14.0 34.0D 42.0 25.0ENaN 18.0
热门推荐