获取dataframe当前数据的行数
时间: 2023-09-03 14:07:48 浏览: 67
可以使用 Pandas 中 DataFrame 的 shape 属性来获取 DataFrame 当前的行数和列数。假设你的 DataFrame 的变量名为 df,那么可以按照如下的方式获取 DataFrame 的行数:
```python
num_rows = df.shape[0]
```
这里的 df.shape[0] 表示获取 df DataFrame 当前的行数。如果要获取 DataFrame 的列数,可以使用 df.shape[1]。需要注意的是,shape 属性返回的是一个元组,其中第一个元素表示 DataFrame 的行数,第二个元素表示 DataFrame 的列数。
相关问题
获取dataframe中获取某数据的当前行数的并获取同一行的另一列数据
可以使用 Pandas 中的 loc 函数来实现。假设你要获取 DataFrame 中某一列为 col_name,该列的值为 target_value 的行的行号,并获取该行的另一列为 another_col_name 的值,可以按照如下的方式实现:
```python
# 假设 DataFrame 名称为 df
row_index = df.loc[df['col_name'] == target_value].index[0] # 获取行号
another_col_value = df.loc[row_index, 'another_col_name'] # 获取同一行的另一列的值
```
这里的第一行代码使用了 loc 函数和条件查询,它会返回一个布尔型的 Series,表示 DataFrame 中哪些行的 col_name 的值等于 target_value,然后使用 index[0] 获取第一个满足条件的行的行号。第二行代码使用 loc 函数和行号来获取同一行的另一列的值,其中 'another_col_name' 是另一列的列名。
对空白dataframe添加数据
要向空白的DataFrame添加数据,可以使用以下方法:
1. 使用字典创建DataFrame并添加数据
```python
import pandas as pd
# 创建空白DataFrame
df = pd.DataFrame(columns=['name', 'age', 'gender'])
# 添加数据
df = df.append({'name': 'Alice', 'age': 25, 'gender': 'F'}, ignore_index=True)
df = df.append({'name': 'Bob', 'age': 30, 'gender': 'M'}, ignore_index=True)
```
2. 使用列表创建DataFrame并添加数据
```python
import pandas as pd
# 创建空白DataFrame
df = pd.DataFrame(columns=['name', 'age', 'gender'])
# 添加数据
df.loc[len(df)] = ['Alice', 25, 'F']
df.loc[len(df)] = ['Bob', 30, 'M']
```
无论哪种方法,都需要指定DataFrame的列名,并使用`append`或`loc`方法添加数据。在使用`loc`方法时,需要指定要添加的行的索引。可以使用`len(df)`来获取当前DataFrame的行数,从而确定新行的索引。