pandas rename column
时间: 2023-10-02 11:03:39 浏览: 50
To rename a column in a pandas DataFrame, you can use the `rename()` method. Here's an example:
```
import pandas as pd
# create a dummy DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
# rename column 'B' to 'C'
df = df.rename(columns={'B': 'C'})
print(df)
```
Output:
```
A C
0 1 4
1 2 5
2 3 6
```
In the `rename()` method, we pass a dictionary where the keys are the old column names and the values are the new column names. In this example, we renamed the column 'B' to 'C'.
相关问题
pandas column重命名
在pandas中,可以使用rename()函数或set_axis()函数来重命名列名。
使用rename()函数,可以通过传递一个字典来指定要重命名的列名和新的列名。例如,如果我们有一个名为df的DataFrame,想要将"Category"列重命名为"Pet",可以使用以下代码:
df.rename(columns={"Category": "Pet"}, inplace=True)
使用set_axis()函数,可以通过传递一个新的列名列表来重新设置列名。例如,如果我们有一个名为df的DataFrame,想要将列名设置为\["Pet", "Color"\],可以使用以下代码:
df.set_axis(\["Pet", "Color"\], axis=1, inplace=True)
请注意,inplace参数用于标记是否在原来的DataFrame上修改列名。如果设置为True,则会直接在原来的DataFrame上修改,如果设置为False,则会返回一个新的DataFrame。
综上所述,根据你的需求,你可以选择使用rename()函数或set_axis()函数来重命名pandas的列名。
#### 引用[.reference_title]
- *1* *3* [pandas重命名列名称、数据列名称重命名(Rename Column Names): rename、set_axis、df.columns](https://blog.csdn.net/zhongkeyuanchongqing/article/details/120867447)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* [Pandas dataframe重命名列名](https://blog.csdn.net/weixin_39829574/article/details/109924724)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
how to rename a column
To rename a column in a pandas DataFrame, you can use the `rename()` method. Here's an example:
```python
import pandas as pd
# Create an example DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
# Rename a specific column
df.rename(columns={'A': 'NewColumn'}, inplace=True)
print(df)
```
Output:
```
NewColumn B
0 1 4
1 2 5
2 3 6
```
In the above code, we use the `rename()` method to rename the column `'A'` to `'NewColumn'`. We pass a dictionary to the `columns` parameter, where the keys are the current column names and the values are the new column names. The `inplace=True` parameter ensures that the DataFrame is modified in-place. If you don't want to modify the original DataFrame, you can assign the result of `rename()` to a new DataFrame or the same variable.