Python Pandas ŌĆō 如何使用 Pandas DataFrame 属性:shape

Python Pandas ŌĆō 如何使用 Pandas DataFrame 属性:shape

编写一个Python程序,从products.csv文件读取数据并打印行和列的数量。然后打印前十行’product’列的值与’Car’匹配。

假设你有一个’products.csv’文件,行和列的数量以及前十行中’product’列值与’Car’匹配的结果分别为

Rows: 100 Columns: 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]计算匹配到’Car’的product列的值

在这里,产品列索引为1,最后打印数据

df1 [df1.iloc [:,1] =='Car']

示例

查看以下代码以更好地了解-

import pandas as pd
df = pd.read_csv('products.csv ')
print("Rows:",df.shape[0],"Columns:",df.shape[1])
df1 = df.iloc [0:10,:]
print(df1[df1.iloc[:,1]=='Car'])

输出

Rows: 100 Columns: 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

解决方案2

  • 从 products.csv 文件中读取数据并将其分配给df
df = pd.read_csv('products.csv ')
  • 打印行数 = df.shape [0]和列数 = df.shape [1]

  • 使用df.head(10)获取前十行并将其分配给df

df1 = df.head(10)
  • 使用以下方法获取与Car匹配的product列的值
df1 [df1 ['product'] =='Car']

现在,让我们检查其实现以更好地了解-

示例

import pandas as pd
df = pd.read_csv('products.csv ')
print("Rows:",df.shape[0],"Columns:",df.shape[1])
df1 = df.head(10)
print(df1[df1['product']=='Car'])

输出

Rows: 100 Columns: 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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程