简体   繁体   English

Python如何在数据框中替换列的值

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

If there is a column called date in a pandas.DataFrame , For which the values are: 如果pandas.DataFrame存在名为date的列,则其值为:

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

How do I change all the values to integers? 如何将所有值更改为整数? For example: 例如:

'20180201', 
'20180202',
 ...

You can use .str.replace() like: 您可以像这样使用.str.replace()

Code: 码:

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

or if not using a regex, faster as a list comprehension like: 或者,如果不使用正则表达式,则可以更快地实现列表理解,例如:

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

Test Code: 测试代码:

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)

Results: 结果:

         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