簡體   English   中英

Python如何在數據框中替換列的值

[英]Python how to replace a column's values in dataframe

如果pandas.DataFrame存在名為date的列,則其值為:

'2018-02-01', 
'2018-02-02',
 ...

如何將所有值更改為整數? 例如:

'20180201', 
'20180202',
 ...

您可以像這樣使用.str.replace()

碼:

df['newdate'] = df['date'].str.replace('-', '')

或者,如果不使用正則表達式,則可以更快地實現列表理解,例如:

df['newdate'] = [x.replace('-', '') for x in df['date']]

測試代碼:

df = pd.DataFrame(['2018-02-01', '2018-02-02'], columns=['date'])
print(df)

df['newdate'] = df['date'].str.replace('-', '')
print(df)

df['newdate2'] = [x.replace('-', '') for x in df['date']]
print(df)

結果:

         date
0  2018-02-01
1  2018-02-02

         date   newdate
0  2018-02-01  20180201
1  2018-02-02  20180202

         date   newdate  newdate2
0  2018-02-01  20180201  20180201
1  2018-02-02  20180202  20180202

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM