python dataframe 重命名
时间: 2023-08-28 08:18:15 浏览: 133
如果你想在Python中重命名DataFrame的列名,你可以使用`rename()`方法或直接对`columns`属性进行赋值操作。下面是两种方法的示例代码:
方法1:使用`rename()`方法
```
import pandas as pd
data = {'A': [1, 2, 3], 'B': [4, 5, 6]}
df = pd.DataFrame(data)
df.rename(columns={'A': 'New_Name'}, inplace=True)
print(df)
```
输出:
```
New_Name B
0 1 4
1 2 5
2 3 6
```
方法2:直接赋值给`columns`属性
```
import pandas as pd
data = {'A': [1, 2, 3], 'B': [4, 5, 6]}
df = pd.DataFrame(data)
df.columns = ['New_Name', 'B']
print(df)
```
输出:
```
New_Name B
0 1 4
1 2 5
2 3 6
```
希望这些代码对你有帮助!<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* [【python】pandas-DataFrame类型数据重命名列表头](https://blog.csdn.net/qq_41539778/article/details/131244010)[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^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
- *3* [python 修改dataframe列名的几种方法](https://blog.csdn.net/bingbangx/article/details/119909306)[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^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文