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

时间:2018-03-30 00:49:36

标签: python pandas dataframe replace

如果date中有一个名为pandas.DataFrame的列,其值为:

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

如何将所有值更改为整数?例如:

'20180201', 
'20180202',
 ...

1 个答案:

答案 0 :(得分:4)

您可以使用.str.replace()之类的:

代码:

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

或者如果不使用正则表达式,则更快地像list comprehension那样:

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