微信登录

pandas列级astype("float64")替换数据类型

列级 - astype("float64") - 替换数据类型

作用:第一次是为了下方可以替换

  1. import numpy as np
  2. import pandas as pd
  3. df["人数"] = df["人数"].astype("str") # 改为str
  4. data = df.astype("int") # 类型转换
  5. data = df.astype("int64") # 类型转换
  6. data = df.astype("int64", copy=False) # 不与原数据关联
  7. data = df.astype({"管理域": "int32"}) # 指定字段转指定类型
  8. df["A"] = df["A"].replace({"$":"",",":""}, regex = True) # float前去掉逗号
  9. data = df.astype("float")
  10. data = df.astype("object")
df["b_col"] = pd.to_datetime(df["b_col"])  # 字符串转成pandas日期格式
df["timestamp"] = df["order_dt"].apply(lambda x: int(x.timestamp()))  # pandas日期格式转成时间戳(有缺陷:要设置时区,否则会错误,用下面的apply方法)
df["order_dt"]=pd.to_datetime(df.order_dt,format="%Y%m%d")
df["order_dt"]=pd.to_datetime(df.order_dt,format="%H:%M:%S")
df["order_dt"]=pd.to_datetime(df.order_dt,format="%Y-%m-%d %H:%M:%S")
df["date_str"] = df["date_str"].dt.strftime("%Y-%m-%d %H:%M:%S")  # 转成字符串
df["time"] = df["ctime"].apply(lambda x: time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(x)))  # 时间戳转日期

时间字符串转时间戳

import time
df["目标列名"] = df.apply(time_tran, args=("列名",), axis=1)

def time_tran(df, role):
    timeArray = time.strptime(df[role], "%Y-%m-%d %H:%M:%S")
    t1 = time.mktime(timeArray)
    return t1