Python Pandas-从CSV文件中读取数据并为前十行打印“产品”列值与“汽车”匹配
假设您有“ products.csv ‘文件和一些行和列的结果,“产品”列值与前十行匹配为“汽车”-
在这里下载products.csv文件 这里 。
行:100 列:8
id product engine avgmileage price height_mm width_mm productionYear
1 2 Car Diesel 21 16500 1530 1735 2020
4 5 Car Gas 18 17450 1530 1780 2018
5 6 Car Gas 19 15250 1530 1790 2019
8 9 Car Diesel 23 16925 1530 1800 2018
我们有两个不同的解决方案。
解决方案1
- 从 products.csv 文件中读取数据并分配给df。
df = pd.read_csv('products.csv ')
- 打印行数= df.shape[0]和列数= df.shape[1]
-
使用iloc [0:10,:] 从df中筛选前十行,将其设置为df1。
df1 = df.iloc[0:10,:]
- 使用df1.iloc [:,1]计算与汽车匹配的产品列值
在这里,产品列索引为1,最后打印数据
df1[df1.iloc[:,1]=='Car']
示例
让我们检查以下代码以更好地理解
import pandas as pd
df = pd.read_csv('products.csv ')
print("行数:",df.shape[0],"列数:",df.shape[1])
df1 = df.iloc[0:10,:]
print(df1[df1.iloc[:,1]=='Car'])
解决方案2
- 从 products.csv 文件中读取数据并分配给df。
df = pd.read_csv('products.csv ')
- print打印行数= df.shape[0]和列数= df.shape[1]
-
取用df.head(10)中的前十行并分配给df。
df1 = df.head(10)
- 使用以下方法获取匹配车辆的产品列值
df1[df1['product']=='Car']
示例
现在,让我们检查其实现以更好地理解
import pandas as pd
df = pd.read_csv('products.csv ')
print("行数:",df.shape[0],"列数:",df.shape[1])
df1 = df.head(10)
print(df1[df1['product']=='Car'])
输出结果
行数:100 列数:8id product engine avgmileage price height_mm width_mm productionYear
1 2 Car Diesel 21 16500 1530 1735 2020
4 5 Car Gas 18 17450 1530 1780 2018
5 6 Car Gas 19 15250 1530 1790 2019
8 9 Car Diesel 23 16925 1530 1800 2018
极客教程