Python Pandas - 按列名对 DataFrame 进行子集
要按列名创建DataFrame的子集,请使用方括号。使用带有方括号(索引运算符)和特定列名称的DataFrame,如下所示-
dataFrame[‘column_name’]
首先,使用别名导入所需的库-
import pandas as pd
使用产品记录创建PandasDataFrame-
dataFrame = pd.DataFrame({"Product": ["SmartTV", "ChromeCast", "Speaker", "Earphone"], "Opening_Stock": [300, 700, 1200, 1500], "Closing_Stock": [200, 500, 1000, 900]})
让我们获取一个子集,即我们只获取Product列记录
dataFrame['Product']
示例
以下是代码
import pandas as pd dataFrame = pd.DataFrame({"Product": ["SmartTV", "ChromeCast", "Speaker", "Earphone"],"Opening_Stock": [300, 700, 1200, 1500],"Closing_Stock": [200, 500, 1000, 900]}) print"DataFrame...\n",dataFrame print"\nDisplaying a subset:\n",dataFrame['Product']输出结果
这将产生以下输出
DataFrame... Closing_Stock Opening_Stock Product 0 200 300 SmartTV 1 500 700 ChromeCast 2 1000 1200 Speaker 3 900 1500 Earphone Displaying a subset: 0 SmartTV 1 ChromeCast 2 Speaker 3 Earphone Name: Product, dtype: object