首页 > 解决方案 > 如何在 Python 中从 pandas DataFrame 中删除字符串的一部分

问题描述

我有这个数据框:

df=pd.DataFrame({'a': [2, 6, 8, 9],
                'date': ['2021-07-21 04:34:02', 
                         'test_2022-17-21 04:54:22',
                        'test_2020-06-21 04:34:02',
                        '2023-12-01 11:54:52']})

df["date"].replace("test_", "")
df

我想从日期列中删除“test_”。也许,你可以帮忙

标签: python-3.xpandasdataframe

解决方案


用于str.strip(<unnecessary string>)删除不必要的字符串:

df.date = df.date.str.strip('test_')

输出:

   a                 date
0  2  2021-07-21 04:34:02
1  6  2022-17-21 04:54:22
2  8  2020-06-21 04:34:02
3  9  2023-12-01 11:54:52

推荐阅读