Pandas的双括号索引[[]]

2024-04-24 20:05:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经看过了谷歌的机器学习速成课程,他们有一个练习,教你如何使用熊猫和tensorflow。在开始时,他们获取数据帧,然后直接获取“总房间数”和“平均值”。他们用双括号表示“总房间数”的系列,而只有一组括号的“中位数”系列。我通读了panda的文档,似乎您需要使用双括号索引到一个系列中的唯一原因是一次索引2列,即数据california_housing_dataframe[[“中值”“house_value”,“total_rooms”]]。为什么他们使用双括号来索引dataframe中的一列,而在以后使用单括号来做同样的事情,原因是什么?在

这是我说的代码。在

california_housing_dataframe = pd.read_csv("https://dl.google.com/mlcc/mledu-datasets/california_housing_train.csv", sep=",")
# Define the input feature: total_rooms.
my_feature = california_housing_dataframe[["total_rooms"]]
# Configure a numeric feature column for total_rooms.
feature_columns = [tf.feature_column.numeric_column("total_rooms")]

targets = california_housing_dataframe["median_house_value"]

如果您需要更多上下文,下面是更多代码:

^{pr2}$

如果您需要更多的上下文,这里是指向练习的链接以及所有代码: https://colab.research.google.com/notebooks/mlcc/first_steps_with_tensor_flow.ipynb?utm_source=mlcc&utm_campaign=colab-external&utm_medium=referral&utm_content=firststeps-colab&hl=en


Tags: 代码dataframe原因columnfeature括号housetotal
2条回答

单括号生成pandas的序列,而双括号生成pandas的数据帧。在

下面是一个例子:

d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)
df
   col1 col2
0   1   3
1   2   4

现在让我们同时使用双括号和单括号打印类型。在

单支架产生:

^{pr2}$

双括号表示:

type(df[["col1"]])
pandas.core.frame.DataFrame

现在你看到了区别,单括号和双括号索引的区别有两个不同的目的。如果要从数据帧中的现有列创建新的数据帧,请使用双括号。在

还有一个类似的答案,还有更多的解释。The difference between double brace `[[...]]` and single brace `[..]` indexing in Pandas

我的特性是一个<class 'pandas.core.frame.DataFrame'>

目标是一个<classpandas.core.series.Series'>

但许多函数都在这两种数据结构上工作。我甚至可以将两者都传递给matplotlib函数。在

在研究差异时,我发现它已经被解释了here

import pandas as pd
import tensorflow as tf
import matplotlib.pyplot as plt

california_housing_dataframe = pd.read_csv("https://dl.google.com/mlcc/mledu-datasets/california_housing_train.csv", sep=",")
# Define the input feature: total_rooms.
my_feature = california_housing_dataframe[["total_rooms"]]
print(type(my_feature))
# Configure a numeric feature column for total_rooms.
feature_columns = [tf.feature_column.numeric_column("total_rooms")]

targets = california_housing_dataframe["median_house_value"]
print(type(targets))

print( my_feature.describe())
print( targets.describe())

print( my_feature.head())
print( targets.head())

print( my_feature.max())
print( targets.max())

相关问题 更多 >