【问题标题】:How to convert value datatype in pandas column with JSON from big number to int64?如何将带有 JSON 的 pandas 列中的值数据类型从大数字转换为 int64?
【发布时间】:2022-11-18 03:34:59
【问题描述】:

我正在使用 read_gbq 读取一个嵌套的 Bigquery 表并获取一些大数字的 json 列表

data = pd.read_gbq(sql, project_id=project)

这是其中一个带有 json 数组的单元格

[{'key': 'firebase_screen_id', 'value': {'string_value': None, 'int_value': -2.047602554786245e+18, 'float_value': None, 'double_value': None}},
 {'key': 'ga_session_id', 'value': {'string_value': None, 'int_value': 1620765482.0, 'float_value': None, 'double_value': None}}]

里面是 'int_value': -2.047602554786245e+18 但它应该是 -2047602554786245165

我试图将列转换为字符串

data['events'].astype(str)

然后是 int 然后是 string

data.astype("Int64").astype(str))

但它仍然是一个带有数组的对象,并且在 t 中修改了大数字

我怎样才能在这个单元格中得到完整的整数以及如何将它应用到列中?

[{'key': 'firebase_screen_id', 'value': {'string_value': None, 'int_value': -2047602554786245165, 'float_value': None, 'double_value': None}},
 {'key': 'ga_session_id', 'value': {'string_value': None, 'int_value': 1620765482.0, 'float_value': None, 'double_value': None}}]

【问题讨论】:

    标签: python arrays pandas


    【解决方案1】:

    通过进一步调查,我发现这个值是浮动的,并用这个函数得出 不是 Exceptions 的最佳使用,但一次很好

    def values_to_int(json_data):
        result = {}
        for c in json_data:
            value = [e for c, e in c['value'].items() if e or e == 0]
            result[c["key"]] = value
            try:
                if type(result["firebase_screen_id"][0]) == float:
                    result["firebase_screen_id"][0] = int(result["firebase_screen_id"][0])
            except Exception:
                continue
        return result
    
    data[col] = data[col].apply(lambda x: values_to_int(x))
    

    【讨论】:

      猜你喜欢
      • 2019-10-11
      • 2013-09-15
      • 2020-12-18
      • 2021-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-20
      相关资源
      最近更新 更多