
我有一个数据框,其中包含由这种格式的字符串组成的日期列。我需要去掉字符串的末尾,以便可以转换为日期时间对象。
"20231101 05:00:00 america/new_york" "20231101 06:00:00 america/new_york"
我尝试过这些方法但没有成功。
df['Date'] = df['Date'].replace('^.*\]\s*', '', regex=True)
df['Date'] = df['Date'].str.strip(' America/New_York')
df['Date'] = df['Date'].map(lambda x: x.rstrip(' America/NewYork'))``以及根据我的搜索得出的其他一些内容。有没有一种简单的方法可以做到这一点,或者我应该编写一个函数来通过抓取前 17 个字符并将结果分配回 df 来对字符串进行切片。
请注意,字符串的格式可能为 '20231101 05:00:00 america/central'
感谢您提供的所有帮助。
new_york,有时会编写不带下划线的 newyork。如果您要求删除 'newyork',则 'new_york' 将不会被删除。'america' 开头,但后面有所不同;在这种情况下,您可以使用 str.split(' america').str[0] 保留 ' america' 之前的所有内容。import pandas as pd
df = pd.DataFrame({
'Name': ['Alice', 'Bob', 'Charlie'],
'Date': ["20231101 05:00:00 America/New_York",
"20231101 06:00:00 America/New_York",
"20231101 07:00:00 America/Central"]
})
# df['Date'] = df['Date'].str.removesuffix(' America/New_York')
df['Date'] = df['Date'].str.split(' America').str[0]
print(df)
# Name Date
# 0 Alice 20231101 05:00:00
# 1 Bob 20231101 06:00:00
# 2 Charlie 20231101 07:00:00
以上就是Pandas 从一列字符串中删除字符的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号