【问题标题】:How to convert Pandas DataFrame to byte array and retrieve it back using numpy rec arrays如何将 Pandas DataFrame 转换为字节数组并使用 numpy rec 数组将其取回
【发布时间】:2017-11-16 05:01:03
【问题描述】:

请仔细阅读代码,我在其中提到了问题。

import numpy as np
import pandas as pd

print("hello")
data = np.array([['', 'Col1', 'Col2'], ['Row1', 1, 2], ['Row2', 3, 4]])
df = pd.DataFrame(data=data[1:, 1:], columns=data[0, 1:])
print(df)

df_to_records = df.to_records(index=False)

records_to_bytes = df_to_records.tobytes()

'''
encryption, decryption code here using cryptography.fernet  . It takes bytes 
as input and gives bytes as output.   
'''
# How can I retrieve DataFrame from records_to_bytes. I can easily retrieve 
# from df_to_records

df_retrieved = pd.DataFrame.from_records(df_to_records)

# What I need is

# df_retrieved = pd.DataFrame.from_records("Inverse operation of 
# df_to_records.tobytes()")

print(df_retrieved)

只要能达到目的,任何替代方法都会受到赞赏: 创建 pandas 框架 --> 将其转换为字节(cryptography.Fernet 将 bytearray 作为输入)。 --> 加密。解密并取回 DataFrame。

【问题讨论】:

    标签: python python-3.x pandas numpy scipy


    【解决方案1】:

    您可以使用numpy.frombuffer,并将dtype 参数显式设置为记录数组的dtype。但是请注意,nummpy.frombuffer 不能在 python Object 类型上运行。如果您的数据框包含字符串,请确保将它们类型转换为 numpy fixed width string types

    【讨论】:

      猜你喜欢
      • 2019-08-04
      • 2020-02-10
      • 1970-01-01
      • 2020-07-12
      • 2020-08-20
      • 1970-01-01
      • 2019-04-21
      • 1970-01-01
      • 2018-12-27
      相关资源
      最近更新 更多