python获取数据行列数
Python作为一种高级编程语言,有很多能力强大的库和工具,其中Pandas库是最常用的数据处理和分析工具之一。在Pandas库中,获取数据的行列数是一个常见的任务。本文将从多个角度分析Python如何获取数据行列数。
一、使用shape属性获取行列数
Pandas库中的DataFrame对象和Series对象都有一个shape属性,该属性返回一个元组,其中第一个元素是行数,第二个元素是列数。下面是一个示例代码:
``` python
import pandas as pd
#创建一个DataFrame
data = {'name': ['John', 'Mary', 'Peter', 'Michael'],
'age': [18, 21, 19, 20],
'gender': ['M', 'F', 'M', 'M']}
df = pd.DataFrame(data)
#获取DataFrame的行列数
row_num, col_num = df.shape
print('The number of rows is:', row_num)
print('The number of columns is:', col_num)
```
输出结果如下:
```
The number of rows is: 4
The number of columns is: 3
```
二、使用len()函数获取行数
Pandas库中的DataFrame对象和Series对象都可以使用len()函数获取行数。例如,下面的代码返回DataFrame对象的行数:
``` python
import pandas as pd
#创建一个DataFrame
data = {'name': ['John', 'Mary', 'Peter', 'Michael'],
'age': [18, 21, 19, 20],
'gender': ['M', 'F', 'M', 'M']}
df = pd.DataFrame(data)
#获取DataFrame的行数
row_num = len(df)
print('The number of rows is:', row_num)
```
输出结果如下:
```
The number of rows is: 4
```
同样地,Series对象也可以使用len()函数获取行数。
三、使用shape[0]和shape[1]获取行列数
除了使用shape属性获取行列数之外,还可以使用shape元组中的第一个元素shape[0]获取行数,使用第二个元素shape[1]获取列数。下面是一个示例代码:
``` python
import pandas as pd
#创建一个DataFrame
data = {'name': ['John', 'Mary', 'Peter', 'Michael'],
'age': [18, 21, 19, 20],
'gender': ['M', 'F', 'M', 'M']}
df = pd.DataFrame(data)
#获取DataFrame的行列数
row_num = df.shape[0]
col_num = df.shape[1]
print('The number of rows is:', row_num)
print('The number of columns is:', col_num)
```
输出结果与使用shape属性获取的结果相同。
四、使用numpy库的shape属性获取行列数
另外一个获取数据行列数的方法是使用numpy库的shape属性。Pandas库中的DataFrame对象和Series对象都可以通过.values属性获得相应的numpy数组,进而获取行列数。下面是一个示例代码:
``` python
import pandas as pd
import numpy as np
#创建一个DataFrame
data = {'name': ['John', 'Mary', 'Peter', 'Michael'],
'age': [18, 21, 19, 20],
'gender': ['M', 'F', 'M', 'M']}
df = pd.DataFrame(data)
#将DataFrame转换为numpy数组
df_array = df.values
#获取数据的行列数
row_num, col_num = np.shape(df_array)
print('The number of rows is:', row_num)
print('The number of columns is:', col_num)
```
结果与之前的示例代码相同。
总结:
Python获取数据的行列数有多个方法,其中包括使用Pandas库的shape属性、len()函数、numpy库的shape属性等。在实际编程中,我们可以根据具体的需求选择适合的方法。