python - 适用于 numpy 数组和 pandas 数据帧的列切片方法

标签 python arrays pandas numpy

示例问题

假设我必须编写一个函数来返回数据表对象的第一列,但我事先不知道该对象是 numpy 2D 数组还是 pandas 2D 数据帧。

到目前为止已尝试过

以下函数适用于 numpy 数组,但不适用于 pandas 数据帧:

def get_first_column(array_or_dataframe):
    return array_or_dataframe[:, 0]

以下函数适用于 pandas 数据帧,但不适用于 numpy 数组:

def get_first_column(array_or_dataframe):
    return array_or_dataframe.iloc[:, 0]

摘要

是否可以编写一个同时适用于 numpy 数组和 pandas 数据帧的列切片表达式?

最佳答案

选项 1
np.asarray

def get_first_column(array_or_dataframe):
    return np.asarray(array_or_dataframe)[:, 0]

选项 2
尝试

def get_first_column(array_or_dataframe):
    try:
        return array_or_dataframe[:, 0]
    except:
        return array_or_dataframe.iloc[:, 0]

演示

df = pd.DataFrame([[1, 2], [3, 4]])

print(get_first_column(df))

print(get_first_column(df.values))

[1 3]
[1 3]

关于python - 适用于 numpy 数组和 pandas 数据帧的列切片方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41221198/

相关文章:

python-2.7 - 从 Pandas 数据帧保存没有双引号的csv文件

python - 使用 Google App Engine 作为简单的键/值存储

java - 如何在没有额外信息的情况下有效地从网页中提取文本

python - Azure Linux Web 应用程序(startup.sh : not found)

c++ - 需要 cdecl 说明 : what is an "array 5?"

javascript - 按键对对象数组进行排序

python - 尝试从 python 脚本执行 golang 程序时出错

计算数组内的十六进制偏移量

python - 为什么我的 Pandas 数据框只显示一个数据集的结果?

python-3.x - 基于条件累积和的多个 Pandas 列