| import pandas as pd | |
| import pyarrow as pa | |
| import pyarrow.ipc as ipc | |
| import numpy as np | |
| import os | |
| # 确保输出目录存在 | |
| output_dir = 'generated_arrow_files' | |
| os.makedirs(output_dir, exist_ok=True) | |
| # 生成 Arrow 文件的函数 | |
| def generate_arrow_file(file_index): | |
| # 创建 Pandas DataFrame(每次生成不同的数据) | |
| data = { | |
| 'integers': np.random.randint(0, 100, size=10), | |
| 'floats': np.random.rand(10), | |
| 'strings': [f'str_{i}' for i in range(10)], | |
| 'booleans': np.random.choice([True, False], size=10) | |
| } | |
| df = pd.DataFrame(data) | |
| # 将 Pandas DataFrame 转换为 PyArrow Table | |
| table = pa.Table.from_pandas(df) | |
| # 写入内存中的字节流 | |
| sink = pa.BufferOutputStream() | |
| with ipc.new_file(sink, table.schema) as writer: | |
| writer.write_table(table) | |
| # 获取字节流并保存为 .arrow 文件 | |
| buffer = sink.getvalue() | |
| file_path = os.path.join(output_dir, f'example_{file_index}.arrow') | |
| with open(file_path, 'wb') as f: | |
| f.write(buffer.to_pybytes()) | |
| print(f"Arrow file {file_index} generated successfully at {file_path}") | |
| # 生成多个文件 | |
| for i in range(5): # 生成5个文件,可以根据需要调整数量 | |
| generate_arrow_file(i) |