@@ -43,41 +43,49 @@ def left_formatter(value):
43
43
return f'{ value :<{w }.{w }s} '
44
44
return left_formatter
45
45
46
- WRAPLEN = 55
46
+ def df_wrapcols ( df , wrap_columns = None ):
47
47
48
- def df_wrapcol (df ,wrap_column = None ,wrap_length = None ):
48
+ if wrap_columns is None : return df
49
+ if not isinstance (wrap_columns ,dict ):
50
+ raise TypeError ('wrap_columns must be a dict of column_names and wrap_lengths' )
49
51
50
- if wrap_column is None : return df
51
- if wrap_length is None : return df
52
+ for col in wrap_columns :
53
+ if col not in df .columns :
54
+ raise ValueError ('column "' + str (col )+ '" not found in df.columns' )
52
55
53
56
index = []
54
- columns = {}
57
+ column_data = {}
55
58
for col in df .columns :
56
- columns [col ] = []
57
- nonwrapcols = [col for col in df .columns if col != wrap_column ]
58
-
59
+ column_data [col ] = []
60
+
59
61
for ix in df .index :
60
62
row = df .loc [ix ,]
61
-
62
- swrap = str (row [wrap_column ])
63
- tw = textwrap .wrap (swrap ,wrap_length ) if not swrap .isspace () else [' ' ]
64
-
65
- columns [wrap_column ].append (tw [0 ])
66
- index .append (str (ix ))
67
- for col in nonwrapcols :
68
- columns [col ].append (row [col ])
69
-
70
- if len (tw ) > 1 :
71
- for r in range (1 ,len (tw )):
72
- columns [wrap_column ].append (tw [r ])
73
- index .append (str (ix )+ '.' + str (r ))
74
- for col in nonwrapcols :
75
- columns [col ].append (' ' )
76
-
77
- return pd .DataFrame (columns ,index = index )
78
-
79
-
80
- df = df_wrapcol (df ,wrap_column = 'Description' ,wrap_length = WRAPLEN )
63
+
64
+ row_data = {}
65
+ for col in row .index :
66
+ cstr = str (row [col ])
67
+ if col in wrap_columns :
68
+ wlen = wrap_columns [col ]
69
+ tw = textwrap .wrap (cstr ,wlen ) if not cstr .isspace () else [' ' ]
70
+ else :
71
+ tw = [cstr ]
72
+ row_data [col ] = tw
73
+
74
+ cmax = max (row_data ,key = lambda k : len (row_data [k ]))
75
+ rlen = len (row_data [cmax ])
76
+ for r in range (rlen ):
77
+ for col in row .index :
78
+ extension = [' ' ]* (rlen - len (row_data [col ]))
79
+ row_data [col ].extend (extension )
80
+ column_data [col ].append (row_data [col ][r ])
81
+ ixstr = str (ix )+ '.' + str (r ) if r > 0 else str (ix )
82
+ index .append (ixstr )
83
+
84
+ return pd .DataFrame (column_data ,index = index )
85
+
86
+ WRAPLEN = 55
87
+
88
+ df = df_wrapcols (df ,wrap_columns = {'Description' :WRAPLEN })
81
89
print ('===========================' )
82
90
print ('dfnew1=' ,df )
83
91
0 commit comments