python dataframe add
时间: 2023-10-13 14:19:57 浏览: 69
Python如何在DataFrame增加数值
To add a new column to a Python dataframe, you can use the following syntax:
```
df['new_column_name'] = new_column_values
```
where `df` is the name of the dataframe, `new_column_name` is the name of the new column you want to add, and `new_column_values` is a list or array of the same length as the number of rows in the dataframe.
For example, let's say you have a dataframe `df` with columns `A` and `B`, and you want to add a new column `C` containing the sum of `A` and `B`:
```python
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
df['C'] = df['A'] + df['B']
print(df)
```
This will output:
```
A B C
0 1 4 5
1 2 5 7
2 3 6 9
```
You can also add a new column with a single value for all rows:
```python
df['D'] = 'new_value'
```
This will add a new column `D` with the value `'new_value'` for all rows in the dataframe.
阅读全文