我正在尝试创建一个接收列表并生成子集索引的函数。如果没有提供索引,我希望它能回馈整个索引。
我认为None
在pandas
工作,但显然不是......我正在使用pandas '0.23.4'
是否有另一个值,我可以给切片方法,如下所示:df.loc[:,"sepal_length"]
,我可以分配给变量?我不能做index=:
df = X_iris.copy()
print(df.columns, df.index[:5], "", sep="\n")
# Index(['sepal_length', 'sepal_width', 'petal_length', 'petal_width'], dtype='object')
# Index(['iris_0', 'iris_1', 'iris_2', 'iris_3', 'iris_4'], dtype='object')
def example(df, index):
result = df.loc[index,"sepal_length"]
print("index =", index, "works")
return result
example(df, "iris_0")
# index = iris_0 works
# 5.1
example(df, None)
# TypeError: cannot use label indexing with a null key
使用slice(None)
:
df
sepal_length sepal_width petal_length petal_width
iris_0 x x x x
iris_1 x x x x
iris_2 x x x x
iris_3 x x x x
iris_4 x x x x
df.loc['iris_0', "sepal_length"]
# 'x'
df.loc[slice(None), "sepal_length"]
iris_0 x
iris_1 x
iris_2 x
iris_3 x
iris_4 x
Name: sepal_length, dtype: object
在对基础NumPy数组进行索引时,您还可以使用Ellipsis
(...
):
# df.to_numpy()[..., df.columns.get_loc('sepal_length')]
df.values[..., df.columns.get_loc('sepal_length')]
# array(['x', 'x', 'x', 'x', 'x'], dtype=object)