Python Pandas - 根据索引在列中选取具体值来创建子集
要创建子集,请根据索引从列中选择特定值,使用iloc()方法。我们首先导入pandas库
import pandas as pd
使用产品记录创建Pandas DataFrame。其中有3列
dataFrame = pd.DataFrame({"Product": ["SmartTV", "ChromeCast", "Speaker", "Earphone"], "Opening_Stock": [300, 700, 1200, 1500],"Closing_Stock": [200, 500, 1000, 900]})
使用iloc()创建子集,其中包含2列和前2行
print"\nDisplaying a subset using iloc() = \n",dataFrame.iloc[0:2, 0:2]
示例
以下为完整代码
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'] # creating a subset with 2 columns and 1st 2 rows using iloc() print"\nDisplaying a subset using iloc() = \n",dataFrame.iloc[0:2, 0:2]
输出
这将产生以下输出
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 Displaying a subset using iloc() = Closing_Stock Opening_Stock 0 200 300 1 500 700
广告