@@ -130,25 +130,12 @@ def from_dict(cls, data: dict[str, Any]) -> Self:
130
130
131
131
def transpose (self ) -> DataTable :
132
132
# Transpose the cells, turning rows into columns
133
-
134
- # Get the list of lists of cell values (i.e., extract all row cells)
135
133
cells_matrix = [row .cells for row in self .rows ]
136
134
137
- # Check the maximum number of columns (to handle different row lengths)
138
- max_columns = max (len (row ) for row in cells_matrix )
139
-
140
- # Create a list to store the transposed cells
141
- transposed_cells = []
142
-
143
- for col_idx in range (max_columns ):
144
- # Create a new list for each transposed column
145
- transposed_column = []
146
- for row in cells_matrix :
147
- transposed_column .append (row [col_idx ])
148
-
149
- # Create a new row from the transposed column
150
- transposed_row = Row (id = str (col_idx ), location = self .location , cells = transposed_column )
151
- transposed_cells .append (transposed_row )
135
+ # Use zip to transpose the matrix and create transposed rows
136
+ transposed_cells = [
137
+ Row (id = str (i ), location = self .location , cells = list (col )) for i , col in enumerate (zip (* cells_matrix ))
138
+ ]
152
139
153
140
# Return a new DataTable with transposed rows
154
141
return DataTable (location = self .location , rows = transposed_cells )
@@ -158,19 +145,12 @@ def to_dict(self) -> dict[str, list[str]]:
158
145
if len (self .rows ) < 2 :
159
146
raise ValueError ("DataTable needs at least two rows: one for headers and one for values" )
160
147
161
- # Extract the header row (first row)
148
+ # Extract the header row and the value rows
162
149
header = [cell .value for cell in self .rows [0 ].cells ]
163
-
164
- # Extract the values from subsequent rows
165
150
values_rows = [[cell .value for cell in row .cells ] for row in self .rows [1 :]]
166
151
167
- # Transpose the values so that each column corresponds to a header key
168
- transposed_values = list (zip (* values_rows ))
169
-
170
- # Map each header to the corresponding list of values
171
- result_dict = {header [i ]: list (transposed_values [i ]) for i in range (len (header ))}
172
-
173
- return result_dict
152
+ # Transpose values and map headers to columns
153
+ return {key : list (values ) for key , values in zip (header , zip (* values_rows ))}
174
154
175
155
176
156
@dataclass
0 commit comments