gpt4 book ai didi

python - 尝试通过标题获取数据框列时出现类型错误

转载 作者:行者123 更新时间:2023-12-01 00:21:40 26 4
gpt4 key购买 nike

我已将 sklearn 中的一个内置数据集加载到 pandas 数据框中。我想从单个列中提取数据,如该列标题所指定的那样。但是,这会产生类型错误,我不明白为什么。下面是 MWE,任何帮助将不胜感激。

import pandas as pd
from sklearn.datasets import load_breast_cancer
meh = load_breast_cancer()

X = pd.DataFrame(meh.data, columns=[meh.feature_names])

# Prints nice dataframe
print(X)

# TypeError: only integer scalar arrays can be converted to a scalar index
print(X["mean radius"])

最佳答案

问题是您使用传递嵌套列表创建了 MultiIndex,因此有必要仅删除 []:

X = pd.DataFrame(meh.data, columns=meh.feature_names)

print(X.columns)
Index(['mean radius', 'mean texture', 'mean perimeter', 'mean area',
'mean smoothness', 'mean compactness', 'mean concavity',
'mean concave points', 'mean symmetry', 'mean fractal dimension',
'radius error', 'texture error', 'perimeter error', 'area error',
'smoothness error', 'compactness error', 'concavity error',
'concave points error', 'symmetry error', 'fractal dimension error',
'worst radius', 'worst texture', 'worst perimeter', 'worst area',
'worst smoothness', 'worst compactness', 'worst concavity',
'worst concave points', 'worst symmetry', 'worst fractal dimension'],
dtype='object')

详细信息:

X = pd.DataFrame(meh.data, columns=[meh.feature_names])
print(X.columns)

MultiIndex([( 'mean radius',),
( 'mean texture',),
( 'mean perimeter',),
( 'mean area',),
( 'mean smoothness',),
( 'mean compactness',),
( 'mean concavity',),
( 'mean concave points',),
( 'mean symmetry',),
( 'mean fractal dimension',),
( 'radius error',),
( 'texture error',),
( 'perimeter error',),
( 'area error',),
( 'smoothness error',),
( 'compactness error',),
( 'concavity error',),
( 'concave points error',),
( 'symmetry error',),
('fractal dimension error',),
( 'worst radius',),
( 'worst texture',),
( 'worst perimeter',),
( 'worst area',),
( 'worst smoothness',),
( 'worst compactness',),
( 'worst concavity',),
( 'worst concave points',),
( 'worst symmetry',),
('worst fractal dimension',)],
)

关于python - 尝试通过标题获取数据框列时出现类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58917019/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com