【问题标题】:What to assign to a variable to act like ":" in pandas dataframe .loc method?在 pandas dataframe .loc 方法中分配什么给变量以像“:”一样?
【发布时间】:2019-07-14 18:30:21
【问题描述】:

我正在尝试创建一个接收列表并生成子集索引的函数。如果没有提供索引,我希望它还给我整个索引。

我认为 Nonepandas 中适用于此,但显然不是...我正在使用 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)大概

标签: python pandas dataframe slice


【解决方案1】:

使用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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-22
    • 2023-01-26
    • 1970-01-01
    • 1970-01-01
    • 2022-06-11
    • 2011-01-27
    • 1970-01-01
    • 2020-11-14
    相关资源
    最近更新 更多