📅  最后修改于: 2020-10-29 03:11:46             🧑  作者: Mango
DataFrame.loc []用于通过标签或DataFrame中的布尔数组检索行和列的组。它仅使用索引标签,并且如果它存在于调用方DataFrame中,则返回行,列或DataFrame。
DataFrame.loc []是基于标签的,但可以与布尔数组一起使用。
.loc []的允许输入为:
pandas.DataFrame.loc[]
没有
它返回Scalar,Series或DataFrame。
#将Pandas 作为pd导入
import pandas as pd
# Creating the DataFrame
info = pd.DataFrame({'Age':[32, 41, 44, 38, 33],
'Name':['Phill', 'William', 'Terry', 'Smith', 'Parker']})
# Create the index
index_ = ['Row_1', 'Row_2', 'Row_3', 'Row_4', 'Row_5']
# Set the index
info.index = index_
# return the value
final = info.loc['Row_2', 'Name']
# Print the result
print(final)
输出:
William
# importing pandas as pd
import pandas as pd
# Creating the DataFrame
info = 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 index
index_ = ['A', 'B', 'C', 'D', 'E']
# Set the index
info.index = index_
# Print the DataFrame
print(info)
输出:
P Q R S
A 28.0 15.0 11 41.0
B 17.0 23.0 23 NaN
C 14.0 NaN 16 34.0
D 42.0 15.0 32 25.0
E NaN 12.0 42 18.0
现在,我们必须使用DataFrame.loc属性返回DataFrame中存在的值。
# return the values
result = info.loc[:, ['P', 'S']]
# Print the result
print(result)
输出:
P S
A 28.0 41.0
B 17.0 NaN
C14.0 34.0
D 42.0 25.0
ENaN 18.0