網站首頁 編程語言 正文
輸入:
$a $b $c $d $e 0 1 2 3 4 5
?期望的輸出:
? ?a ?b ?c ?d ?e
0 ?1 ?2 ?3 ?4 ?5
原數據DataFrame:
import pandas as pd df = pd.DataFrame({'$a': [1], '$b': [2], '$c': [3], '$d': [4], '$e': [5]})
解決方法1:通過DataFrame.columns類的自身屬性修改
1. 暴力修改
df.columns = ['a', 'b', 'c', 'd', 'e']
2. stirp 方法
strip() 方法用于移除字符串頭尾指定的字符(默認為空格或換行符)或字符序列。
df.columns = df.columns.str.strip('$')
3. lambda 表達式
map() 會根據提供的函數對指定序列做映射。以參數序列中的每一個元素調用 function 函數,返回包含每次 function 函數返回值的新列表。
lambda x: x[1:]表示取第二個元素,因此列表名$a、$b等只取出a、b。
df.columns = df.columns.map(lambda x: x[1:])
解決方法2:通過DataFrame.rename()函數修改
1. 暴力修改(可以只修改部分列名)
df.rename(columns=('$a': 'a', '$b': 'b', '$c': 'c', '$d': 'd', '$e': 'e'}, inplace=True)
2. lambda 表達式
調用replace函數,把$替換為空。
df.rename(columns=lambda x:x.replace('$',''), inplace=True)
pandas 更改DataFrame的行名或列名實例
更改行名或更改列名可以選用rename函數。
首先,構建一個dataframe:
import pandas as pd d={'one':{'a':1,'b':2,'c':3,'d':4},'two':{'a':5,'b':6,'c':7,'d':8},'three':{'a':9,'b':10,'c':11,'d':12}} df=pd.DataFrame(d) print(df) 1 2 3 4
輸出結果為:
one two three
a 1 5 9
b 2 6 10
c 3 7 11
d 4 8 12
更改列名
將第2列列名更改為twotwo
df.rename(columns={'two':'twotwo'},inplace=True) print(df) 1 2
輸出結果為:
one twotwo three
a 1 5 9
b 2 6 10
c 3 7 11
d 4 8 12
更改行名
將第1行和第2行的行名更改為aa,bb
df.rename(index={'a':'aa','b':'bb'},inplace=True) print(df) 1 2
輸出結果為:
one twotwo three
aa 1 5 9
bb 2 6 10
c 3 7 11
d 4 8 12
更改成功。
當然,也可以選擇暴力更改行名或列名:
df.columns=['onon','twtw','thth'] print(df) 1 2
輸出結果為:
onon twtw thth
aa 1 5 9
bb 2 6 10
c 3 7 11
d 4 8 12
總結
原文鏈接:https://xiaoshuwen.blog.csdn.net/article/details/100066174
相關推薦
- 2021-12-06 linux下ceph分布式安裝使用教程_Linux
- 2022-02-12 OWASP列舉的Web應用程序十大安全漏洞 - SQL注入
- 2022-04-11 python中pip安裝、升級以及升級固定的包_python
- 2022-12-07 C++AVL樹4種旋轉詳講(左單旋、右單旋、左右雙旋、右左雙旋)_C 語言
- 2022-06-16 VS?Code?C++環境的搭建過程_C 語言
- 2022-10-27 scrollview?tableView嵌套解決方案示例_IOS
- 2022-10-23 C#中的yield關鍵字詳解_C#教程
- 2023-02-18 Go語言IO輸入輸出底層原理及文件操作API_Golang
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支