-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathread_parquet.py
More file actions
85 lines (69 loc) · 2.12 KB
/
Copy pathread_parquet.py
File metadata and controls
85 lines (69 loc) · 2.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
read_parquet.py —— 在终端中友好地查看 Parquet 文件
"""
import argparse
import pathlib
import sys
import pandas as pd
import contextlib
def read_parquet(path, columns=None):
"""
读取 parquet 文件;如指定 columns 则只读取相应列
"""
return pd.read_parquet(path, columns=columns)
def show_dataframe(df, n=10, full=False):
"""
在终端打印 DataFrame
"""
if full:
ctx = pd.option_context(
"display.max_columns", None,
"display.max_colwidth", None,
"display.width", None
)
else:
# 不做特殊处理
ctx = contextlib.nullcontext()
with ctx:
print(df.head(n))
def main():
parser = argparse.ArgumentParser(
description="Read a .parquet file and print its contents."
)
parser.add_argument("file", help="Path to parquet file")
parser.add_argument(
"-n", "--num", type=int, default=10,
help="Number of rows to display (default=10)"
)
parser.add_argument(
"--cols", nargs="+",
help="Only load / display specified columns"
)
parser.add_argument(
"--full", action="store_true",
help="Print without pandas truncation (show all columns/full width)"
)
parser.add_argument(
"--info", action="store_true",
help="Print DataFrame.info() before data"
)
args = parser.parse_args()
parquet_path = pathlib.Path(args.file)
if not parquet_path.exists() or not parquet_path.is_file():
print(f"Error: '{parquet_path}' does not exist or is not a file.", file=sys.stderr)
sys.exit(1)
try:
df = read_parquet(parquet_path, columns=args.cols)
except Exception as e:
print(f"Failed to read parquet: {e}", file=sys.stderr)
sys.exit(1)
if args.info:
print("=== DataFrame.info() ===")
print(df.info(show_counts=True))
print()
print(f"=== First {args.num} rows (DataFrame shape={df.shape}) ===")
show_dataframe(df, n=args.num, full=args.full)
if __name__ == "__main__":
main()