網站首頁 編程語言 正文
寫這篇博客主要是因為在修改DataFrame列值的時候經常遇到bug,但到目前還沒把這種錯誤復現(xiàn)出來。
DataFrame是Pandas中的主要數(shù)據(jù)結構之一,本篇博客主要介紹如何DataFrame中某一列的值進行修改。
1 常規(guī)方法
這部分主要介紹修改DataFrame列值的常規(guī)方法。為了方便后續(xù)說明先構建如下數(shù)據(jù):
import pandas as pd
import numpy as np
df=pd.DataFrame([['A',1],['B',2],['C',5],['D',4],['E',10],['F',13],['G',8]],
columns=['col_1','col_2'],
index=list('abcdefg'))
df結果如下:
- 使用常量修改DataFrame列的值
使用一個常量對DataFrame列中的數(shù)據(jù)進行修改時,代碼舉例如下:
df1=df.copy()
df1['col_1']='H'
df1.loc[['a','c','d'],'col_2']=100 #將指定索引的列值進行修改
df1.iloc[4:,-1]=200
df1的結果如下:
- 使用List\array修改DataFrame列的值
當需要對DataFrame列中的多個值進行修改時,可以使用List或array等變量型數(shù)據(jù)來對其進行修改。具體代碼如下:
df2=df.copy()
df2['col_1']=list(range(7))
df2.loc[df2.index<='d','col_2']=np.array([15,20,25,30])
df2.iloc[4:,-1]=np.array([10,5,0])
df2的結果如下:
- 使用Series/DataFrame修改DataFrame列的值
除了以上兩種數(shù)據(jù)類型之外,還可以使用Series型數(shù)據(jù)來修改DataFrame列的值。但使用這種方法時,需要索引對齊,否則會出錯。具體舉例如下:
df3=df.copy()
df3['col_1']=pd.Series([1,2,3,4,5,6,7]) #索引不對齊時不會報錯,但沒有成功修改列值。
df3.loc[['a','b','c'],'col_2']=pd.Series([100,200,300],index=list('abc'))
df3.iloc[3:,-1]=pd.DataFrame([[4000],[5000],[6000],[7000]],index=list('cdef'))
其結果如下:
2. replace方法
DataFrame對象自帶的方法replace()也可以實現(xiàn)列值的修改。該方法中的參數(shù)主要有以下幾個:
參數(shù) | 作用 |
---|---|
to_replace | 確定需要修改列值的數(shù)據(jù)。可接受的數(shù)據(jù)類型有:str, regex, list, dict, Series, int, float, or None |
value | 指定修改后的值。可接受的數(shù)據(jù)類型有:scalar, dict, list, str, regex, default None |
inplace | 是否本地置換 |
limit | 指定前后填充的最大次數(shù) |
regex | 正則表達式符號。如果需要在to_replace中使用字符串形式的正則表達式對數(shù)據(jù)進行篩選的話,需要將其設置為True。 |
method | 填充方式。‘pad’, ‘ffill’, ‘bfill’, None |
創(chuàng)建如下數(shù)據(jù),具體如下:
df=pd.DataFrame([['A','A'],['B','B'],['C',5],['D',4]],
columns=['col_1','col_2'],
index=list('abcd'))
df的結果如下:
- 對整個DataFrame中的指定數(shù)據(jù)進行替換
#A替換為aaa,B替換為bbb,4替換為100
df_1=df.replace(to_replace=['A','B',4],value=['aaa','bbb',100])
#將A替換為AAAA
df_2=df.replace(to_replace='A',value='AAAA')
#將A替換為AAAAA,5替換為2000
df_3=df.replace(to_replace={"A":'AAAAA',5:2000})
其結果如下:
- 對DataFrame中的不同列指定不同的替換方式
#對于col_1列:將A替換為1,B替換為2
#對于col_2列:將A替換為100,B替換為200
df_4=df.replace({"col_1":{'A':1,'B':2},"col_2":{"A":100,"B":200}})
其結果如下:
- 使用正則表達式篩選數(shù)據(jù)
#將A\B替換成new
df_5=df.replace(to_replace=r'[AB]',value='new',regex=True)
其結果如下:
補充:DataFrame修改某一行某一列的值[坑點]
# df.iloc[index]['column_name'] = val 這種方式是錯誤的
df['column_name'].iloc[i] = val # 正確
總結?
原文鏈接:https://blog.csdn.net/yeshang_lady/article/details/127619031
相關推薦
- 2022-12-24 MobPush?for?Flutter集成準備_IOS
- 2023-04-01 Python使用pptx實現(xiàn)復制頁面到其他PPT中_python
- 2022-02-04 sql語句:and與or的優(yōu)先級
- 2022-12-07 C++?類this及返回自身對象的引用方式_C 語言
- 2022-06-16 Linux系統(tǒng)下Go語言開發(fā)環(huán)境搭建_Golang
- 2022-08-18 golang?select?機制和超時問題_Golang
- 2022-10-03 Golang實現(xiàn)HTTP編程請求和響應_Golang
- 2022-02-26 Uncaught RangeError: Maximum call stack size excee
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細win安裝深度學習環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結構-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支