dataframe添加一列序号
时间: 2023-07-06 19:21:19 浏览: 68
要为一个DataFrame添加一列序号,可以使用`reset_index()`方法来重新设置DataFrame的索引,然后再将索引作为新的一列添加到DataFrame中。
以下是示例代码:
```python
import pandas as pd
# 创建一个DataFrame
df = pd.DataFrame({'name': ['Alice', 'Bob', 'Charlie', 'David'],
'age': [25, 32, 18, 47],
'city': ['Beijing', 'Shanghai', 'Guangzhou', 'Shenzhen']})
# 使用reset_index()方法重新设置索引,并将索引作为新的一列添加到DataFrame中
df['index'] = df.reset_index().index
print(df)
```
输出结果为:
```
name age city index
0 Alice 25 Beijing 0
1 Bob 32 Shanghai 1
2 Charlie 18 Guangzhou 2
3 David 47 Shenzhen 3
```
可以看到,新的一列名为`index`,包含了DataFrame的行号。
相关问题
dataframe添加一行
要向DataFrame添加一行,可以使用以下步骤:
1. 创建一个新的DataFrame,其中包含要添加的行数据。
2. 使用`pandas.concat()`函数将新DataFrame与原始DataFrame进行连接。
3. 使用`pandas.DataFrame.reset_index()`函数重置索引。
下面是一个示例代码,通过向DataFrame添加一行来演示上述步骤:
```python
import pandas as pd
# 创建一个DataFrame
data = {'name': ['Alice', 'Bob', 'Charlie'],
'age': [25, 30, 35],
'gender': ['F', 'M', 'M']}
df = pd.DataFrame(data)
# 创建要添加的新行
new_row = {'name': 'David', 'age': 40, 'gender': 'M'}
# 将新行转换为DataFrame
new_df = pd.DataFrame([new_row])
# 将新DataFrame与原始DataFrame连接
df = pd.concat([df, new_df], ignore_index=True)
# 重置索引
df = df.reset_index(drop=True)
print(df)
```
输出:
```
name age gender
0 Alice 25 F
1 Bob 30 M
2 Charlie 35 M
3 David 40 M
```
dataframe添加一列
要向 DataFrame 添加一列,可以使用以下代码:
```python
import pandas as pd
# 创建一个示例 dataframe
data = {'Name': ['Alice', 'Bob', 'Charlie', 'David'],
'Age': [25, 32, 18, 47],
'Gender': ['F', 'M', 'M', 'M']}
df = pd.DataFrame(data)
# 添加一列
df['City'] = ['Seattle', 'New York', 'Los Angeles', 'Chicago']
print(df)
```
输出结果为:
```
Name Age Gender City
0 Alice 25 F Seattle
1 Bob 32 M New York
2 Charlie 18 M Los Angeles
3 David 47 M Chicago
```
在这个例子中,我们使用 `df['City']` 创建了一个新的列,并将列表 `['Seattle', 'New York', 'Los Angeles', 'Chicago']` 分配给它。您可以根据需要修改列名和数据。