Python Pandas - 使用索引操作符创建子集 DataFrame
索引操作符方括号用于创建子集 dataframe。让我们首先创建一个 Pandas DataFrame。DataFrame 中有 3 列
dataFrame = pd.DataFrame({"Product": ["SmartTV", "ChromeCast", "Speaker", "Earphone"],"Opening_Stock": [300, 700, 1200, 1500],"Closing_Stock": [200, 500, 1000, 900]})
使用单列创建子集
dataFrame[['Product']]
使用多列创建子集
dataFrame[['Opening_Stock','Closing_Stock']]
示例
以下是完整代码
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 using indexing operator:\n",dataFrame[['Product']] print"\nDisplaying a subset with multiple columns:\n",dataFrame[['Opening_Stock','Closing_Stock']]
输出
将产生以下输出
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 using indexing operator: Product 0 SmartTV 1 ChromeCast 2 Speaker 3 Earphone Displaying a subset with multiple columns: Opening_Stock Closing_Stock 0 300 200 1 700 500 2 1200 1000 3 1500 900
广告