Python - 使用 filter() 创建列的子集
要创建列的子集,我们可以使用 filter()。通过此操作,我们可以使用 like 运算符过滤具有相似模式的列值。首先,让我们创建一个包含 3 列的数据框 -
dataFrame = pd.DataFrame({"Product": ["SmartTV", "ChromeCast", "Speaker", "Earphone"],"Opening_Stock": [300, 700, 1200, 1500],"Closing_Stock": [200, 500, 1000, 900]})
现在,让我们创建一个包含多列的子集 -
dataFrame[['Opening_Stock','Closing_Stock']]
创建一个包含模式相似的名称的子集 -
dataFrame.filter(like='Open')
示例
以下是完整代码 -
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']] print"\nDisplaying a subset with similarly patterned names:\n",dataFrame.filter(like='Open')
输出
这将产生以下输出 -
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 Displaying a subset with similarly patterned names: Opening_Stock 0 300 1 700 2 1200 3 1500
广告