【问题标题】:Convert a pandas column of int to timestamp datatype when column name is not known当列名未知时,将 pandas 的 int 列转换为时间戳数据类型
【发布时间】:2023-01-13 16:04:21
【问题描述】:

嗨,我的用例是我有日期时间字段的动态名称,日期类似于 unix timestamp。所以每次都可能有不同的列名并且可以有多个日期归档。那我该怎么做呢?现在,如果我对列名进行硬编码,这对我有用

df['date'] = pandas.to_datetime(df['date'], unit='s')

但不确定如何使用 pandas 为动态名称和多个字段制作这个

【问题讨论】:

  • 您好,您可以使用列索引,例如 df.iloc[:, indx] 吗?
  • 列名是否有模式?
  • @Corralien 不总是随机的和未知的
  • @MohamedAliJAMAOUI 没明白你能举个例子吗?
  • 但是值总是像1673458455这样的数字?

标签: python pandas


【解决方案1】:

正如我的评论所建议的那样,您可以尝试将所有列转换为 DatetimeIndex,然后只保留一个转换成功的列?

# Inspired from @mozway, https://stackoverflow.com/a/75106101/15239951
def find_datetime_col(df):
    mask = df.astype(str).apply(pd.to_datetime, errors='coerce').notna()
    return mask.mean().idxmax()

col = find_datetime_col(df)
print(col)

# Output
Heading 1

输入数据帧:

>>> df
   Heading 1  Heading 2  Heading 3  Heading 4
0 2023-01-01         34         12         34
1 2023-01-02         42         99         42
2 2023-01-03         42         99         42
3 2023-01-04         42         99         42

【讨论】:

    猜你喜欢
    • 2019-08-11
    • 2018-10-09
    • 2021-06-25
    • 2016-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-25
    • 2012-08-19
    相关资源
    最近更新 更多