DataFrame#
- class DataFrame#
Two-dimensional labeled data structure with columns of potentially different types.
Example#
import pandasCore as pd
# Create DataFrame from dict
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
print(df.shape) # (3, 2)
print(df.columns) # ['A', 'B']
Attributes#
Attribute |
Description |
Example |
|---|---|---|
|
The transpose of the DataFrame |
|
|
The column labels of the DataFrame |
|
|
Indicator whether DataFrame is empty |
|
|
Number of columns in the DataFrame |
|
|
Number of rows in the DataFrame |
|
|
Return a PlotAccessor. Not implemented. |
|
|
Return a tuple representing the dimensionality of the DataFrame |
|
|
Return an int representing the number of elements in this object |
|
|
Accessor for sparse data operations |
|
|
Return a Styler object. Not implemented. |
Construction#
Method |
Description |
Example |
|---|---|---|
|
Two-dimensional labeled data structure. |
Indexing / Selection#
Method |
Description |
Example |
|---|---|---|
|
Get column by name |
|
|
Set column values. |
|
|
Select initial periods of time series data based on a date offset. |
|
|
Get item from object for given key (column name). |
|
|
Return the first n rows. |
|
|
Return index of first occurrence of maximum over requested axis. |
|
|
Return index of first occurrence of minimum over requested axis. |
|
|
Select final periods of time series data based on a date offset. |
|
|
Replace values where the condition is True. |
|
|
Return the first n rows ordered by columns in descending order. |
|
|
Return the first n rows ordered by columns in ascending order. |
|
|
Query the columns of a DataFrame with a boolean expression. |
|
|
Return a random sample of items from an axis of object. |
|
|
Return the last n rows. |
|
|
Return the elements in the given positional indices. |
|
|
Replace values where the condition is False. |
|
|
Return cross-section from the Series/DataFrame. |
Data Manipulation#
Method |
Description |
Example |
|---|---|---|
|
Assign new columns to a DataFrame. |
|
|
Drop specified labels from rows or columns. |
|
|
Return DataFrame with requested index / column level(s) removed. |
|
|
Insert column into DataFrame at specified location. |
|
|
Return item and drop from frame. |
|
|
Conform DataFrame to new index with optional filling logic. |
|
|
Rename columns or index labels. |
|
|
Set the name of the axis for the index or columns. |
|
|
Rearrange index levels using input order. |
|
|
Replace values given in to_replace with value. |
|
|
Reset the index, or a level of it. |
|
|
Assign desired index to given axis. |
|
|
Set the DataFrame index using an existing column. |
|
|
Swap levels i and j in a MultiIndex. |
|
|
Modify in place using non-NA values from another DataFrame. |
Missing Data#
Method |
Description |
Example |
|---|---|---|
|
Fill NA/NaN values using next valid observation. |
|
|
Fill NA/NaN values by using the next valid observation to fill gap. |
|
|
Remove missing values. |
|
|
Fill NA/NaN values by propagating the last valid observation forward. |
|
|
Fill NA/NaN values using the specified method. |
|
|
Fill NaN values using an interpolation method. |
|
|
Detect missing values. |
|
|
Detect missing values (alias for isna). |
|
|
Detect non-missing values. |
|
|
Detect non-missing values (alias for notna). |
|
|
Fill NA/NaN values using previous valid observation. |
Statistics#
Method |
Description |
Example |
|---|---|---|
|
Count non-NA cells for each column or row. |
|
|
Return cumulative maximum over a DataFrame axis. |
|
|
Return cumulative minimum over a DataFrame axis. |
|
|
Return cumulative product over a DataFrame axis. |
|
|
Return cumulative sum over a DataFrame axis. |
|
|
Generate descriptive statistics. |
|
|
Return unbiased kurtosis over requested axis. |
|
|
Alias for kurt() |
|
|
Return the maximum of the values over the requested axis. |
|
|
Return the mean of the values over the requested axis. |
|
|
Return the median of the values over the requested axis. |
|
|
Return the minimum of the values over the requested axis. |
|
|
Get the mode(s) of each element along the selected axis. |
|
|
Count number of distinct elements in specified axis. |
|
|
Return the product of the values over the requested axis. |
|
|
Return values at the given quantile over requested axis. |
|
|
Return unbiased standard error of the mean over requested axis. |
|
|
Return unbiased skew over requested axis. |
|
|
Return sample standard deviation over requested axis. |
|
|
Return the sum of the values over the requested axis. |
|
|
Return a Series containing counts of unique rows in the DataFrame. |
|
|
Return unbiased variance over requested axis. |
Aggregation#
Method |
Description |
Example |
|---|---|---|
|
Aggregate using one or more operations over the specified axis. |
|
|
Alias for agg() |
|
|
Apply a function along an axis of the DataFrame. |
|
|
Apply a function to each element of the DataFrame. |
|
|
Provide exponentially weighted (EW) calculations. |
|
|
Provide expanding transformations. |
|
|
Group DataFrame using a mapper or by a Series of columns. |
|
|
Apply a function to each element of the DataFrame. |
|
|
Apply chainable functions that expect DataFrames. |
|
|
Resample time-series data. |
|
|
Provide rolling window calculations. |
|
|
Call func on self producing a DataFrame with transformed values. |
Arithmetic#
Method |
Description |
Example |
|---|---|---|
|
Get Addition of dataframe and other, element-wise. |
|
|
Get Floating division of dataframe and other, element-wise. |
|
|
Compute the matrix multiplication between the DataFrame and other. |
|
|
Get Integer division of dataframe and other, element-wise. |
|
|
Get Modulo of dataframe and other, element-wise. |
|
|
Get Multiplication of dataframe and other, element-wise. |
|
|
Get Exponential power of dataframe and other, element-wise. |
|
|
Get Addition of dataframe and other, element-wise (binary operator … |
|
|
Get Floating division of dataframe and other, element-wise (binary … |
|
|
Get Integer division of dataframe and other, element-wise (binary o… |
|
|
Get Modulo of dataframe and other, element-wise (binary operator rm… |
|
|
Get Multiplication of dataframe and other, element-wise (binary ope… |
|
|
Get Exponential power of dataframe and other, element-wise (binary … |
|
|
Get Subtraction of dataframe and other, element-wise (binary operat… |
|
|
Get Floating division of dataframe and other, element-wise (binary … |
|
|
Get Subtraction of dataframe and other, element-wise. |
|
|
Get Floating division of dataframe and other, element-wise. |
Comparison#
Method |
Description |
Example |
|---|---|---|
|
||
|
||
|
||
|
||
|
||
|
||
|
Compare to another DataFrame and show the differences. |
|
|
Get Equal to of dataframe and other, element-wise. |
|
|
Test whether two objects contain the same elements. |
|
|
Get Greater than or equal to of dataframe and other, element-wise. |
|
|
Get Greater than of dataframe and other, element-wise. |
|
|
Get Less than or equal to of dataframe and other, element-wise. |
|
|
Get Less than of dataframe and other, element-wise. |
|
|
Get Not equal to of dataframe and other, element-wise. |
Sorting#
Method |
Description |
Example |
|---|---|---|
|
Compute numerical data ranks (1 through n) along axis. |
|
|
Sort object by labels (along an axis). |
|
|
Sort by the values along either axis. |
Reshaping#
Method |
Description |
Example |
|---|---|---|
|
Transform each element of a list-like to a row. |
|
|
Unpivot a DataFrame from wide to long format. |
|
|
Return reshaped DataFrame organized by given index / column values. |
|
|
Create a spreadsheet-style pivot table as a DataFrame. |
|
|
Squeeze 1 dimensional axis objects into scalars. |
|
|
Stack the prescribed level(s) from columns to index. |
|
|
Interchange axes and swap values axes appropriately. |
|
|
Transpose index and columns. |
|
|
Pivot a level of the index labels to columns. |
Combining#
Method |
Description |
Example |
|---|---|---|
|
Align two DataFrames on their axes. |
|
|
Perform column-wise combine with another DataFrame. |
|
|
Update null elements with value in the same location in other. |
|
|
Join columns of another DataFrame. |
|
|
Merge DataFrame objects with a database-style join. |
Time Series#
Method |
Description |
Example |
|---|---|---|
|
Convert time series to specified frequency. |
|
|
Return the last row(s) without any NaNs before where. |
|
|
Select values at particular time of day. |
|
|
Select values between particular times of day. |
|
|
First discrete difference of element. |
|
|
Return index for first non-NA value or None, if no non-NA value is … |
|
|
Return index for last non-NA value or None, if no non-NA value is f… |
|
|
Percentage change between the current and a prior element. |
|
|
Shift index by desired number of periods. |
|
|
Convert DataFrame from DatetimeIndex to PeriodIndex. |
|
|
Convert DataFrame from PeriodIndex to DatetimeIndex. |
|
|
Convert tz-aware axis to target time zone. |
|
|
Localize tz-naive index of a DataFrame to target time zone. |
I/O#
Method |
Description |
Example |
|---|---|---|
|
Copy object to the system clipboard. |
|
|
Write object to a comma-separated values (csv) file. |
|
|
Convert the DataFrame to a dictionary. |
|
|
Write object to an Excel sheet. |
|
|
Write a DataFrame to the binary Feather format. Not implemented. |
|
|
Write a DataFrame to a Google BigQuery table. Not implemented. |
|
|
Write the contained data to an HDF5 file using HDFStore. |
|
|
Render a DataFrame as an HTML table. |
|
|
Convert the object to a JSON string. |
|
|
Render object to a LaTeX tabular environment. |
|
|
Print DataFrame in Markdown-friendly format. |
|
|
Convert the DataFrame to a NumPy array. |
|
|
Write a DataFrame to the ORC format. Not implemented. |
|
|
Write a DataFrame to the binary parquet format. Not implemented. |
|
|
Pickle (serialize) object to file. Not implemented. |
|
|
Convert DataFrame to a list of tuples (records). |
|
|
Write records stored in a DataFrame to a SQL database. Not implemen… |
|
|
Export DataFrame object to Stata dta format. Not implemented. |
|
|
Render a DataFrame to a console-friendly tabular output. |
|
|
Return an xarray object from the pandas object. Not implemented. |
|
|
Render a DataFrame to an XML document. |
Conversion#
Method |
Description |
Example |
|---|---|---|
|
Cast a pandas object to a specified dtype. |
|
|
Return the bool of a single element DataFrame. |
|
|
Convert columns to the best possible dtypes using dtypes supporting… |
|
|
Make a copy of this object’s indices and data. |
|
|
Attempt to infer better dtypes for object columns. |
Iteration#
Method |
Description |
Example |
|---|---|---|
|
Check if key is contained in DataFrame columns. |
|
|
Iterate over column names |
|
|
Return the number of rows |
|
|
Iterate over (column name, Series) pairs |
|
|
Iterate over DataFrame rows as (index, dict) pairs |
|
|
Iterate over DataFrame rows as namedtuples |
|
|
Return the column labels (alias for columns property) |
Set Operations#
Method |
Description |
Example |
|---|---|---|
|
Return DataFrame with duplicate rows removed. |
|
|
Return boolean Series denoting duplicate rows. |
|
|
Whether each element in the DataFrame is contained in values. |
Datetime Methods#
Method |
Description |
Example |
|---|---|---|
|
Round a DataFrame to a variable number of decimal places. |
Other Methods#
Method |
Description |
Example |
|---|---|---|
|
||
|
||
|
||
|
Return a DataFrame with absolute numeric value of each element. |
|
|
Prefix labels with string prefix. |
|
|
Suffix labels with string suffix. |
|
|
Return whether all elements are True, potentially over an axis. |
|
|
Return whether any element is True, potentially over an axis. |
|
|
Make a box plot from DataFrame columns. Not implemented. |
|
|
Trim values at input threshold(s). |
|
|
Compute pairwise correlation of columns. |
|
|
Compute pairwise correlation. |
|
|
Compute pairwise covariance of columns. |
|
|
Alias for div() |
|
|
Evaluate a string describing operations on DataFrame columns. |
|
|
Subset the DataFrame rows or columns according to the specified ind… |
|
|
Make a histogram of the DataFrame’s columns. Not implemented. |
|
|
Print a concise summary of a DataFrame |
|
|
Set item by position. |
|
|
Return the memory usage of each column in bytes. |
|
|
Alias for mul() |
|
|
Alias for prod() |
|
|
Return an object with matching indices as other object. |
|
|
Return a subset of the DataFrame’s columns based on the column dtypes. |
|
|
Return a new object with updated flags. |
|
|
Alias for sub() |
|
|
Truncate a Series or DataFrame before and after some index value. |
Code Examples#
The following examples are extracted from the test suite.
T (test_df_sorting_reshaping.py:157)
147 f_print_header("Test: transpose / T")
148
149 try:
150 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]})
151
152 # Test transpose method
153 t1 = df.transpose()
154 f_print_info(f"transpose shape: {t1.shape}")
155
156 # Test T property
157 t2 = df.T
158 f_print_info(f"T property shape: {t2.shape}")
159
160 # Shapes should match
161 if t1.shape == t2.shape:
162 f_print_success("transpose/T: passed")
163 return True
164 else:
165 f_print_error("transpose/T: shapes don't match")
166 return False
columns (test_dataframe.py:43)
33 f_print_header("Test: DataFrame __init__ from dict")
34
35 try:
36 # Create DataFrame from dict
37 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]})
38
39 # Check shape
40 ctx.assert_equal((3, 2), df.shape, "Shape is (3, 2)")
41
42 # Check columns
43 cols = list(df.columns)
44 ctx.assert_true('A' in cols and 'B' in cols, "Columns contain A and B")
45
46 # Check nrows/ncols
47 ctx.assert_equal(3, df.nrows, "nrows is 3")
48 ctx.assert_equal(2, df.ncols, "ncols is 2")
49
50 # Check len
51 ctx.assert_equal(3, len(df), "len(df) is 3")
52
53 # Check __getitem__
empty (test_example.py:65)
55 # Check shape
56 shape = df.shape
57 if shape == (0, 0):
58 f_print_success(f"Shape is correct: {shape}")
59 else:
60 f_print_error(f"Shape is wrong: {shape}, expected (0, 0)")
61 return False
62
63 # Check empty property
64 if df.empty:
65 f_print_success("empty property is True")
66 else:
67 f_print_error("empty property should be True")
68 return False
69
70 # Check len
71 if len(df) == 0:
72 f_print_success("len(df) is 0")
73 else:
74 f_print_error(f"len(df) is {len(df)}, expected 0")
ncols (test_dataframe.py:48)
38 # Check shape
39 ctx.assert_equal((3, 2), df.shape, "Shape is (3, 2)")
40
41 # Check columns
42 cols = list(df.columns)
43 ctx.assert_true('A' in cols and 'B' in cols, "Columns contain A and B")
44
45 # Check nrows/ncols
46 ctx.assert_equal(3, df.nrows, "nrows is 3")
47 ctx.assert_equal(2, df.ncols, "ncols is 2")
48
49 # Check len
50 ctx.assert_equal(3, len(df), "len(df) is 3")
51
52 # Check __getitem__
53 col_a = df['A']
54 ctx.assert_equal(3, len(col_a), "Column A has 3 elements")
55
56 f_print_success("DataFrame __init__ from dict: All checks passed")
57 return True
nrows (test_dataframe.py:47)
37 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]})
38
39 # Check shape
40 ctx.assert_equal((3, 2), df.shape, "Shape is (3, 2)")
41
42 # Check columns
43 cols = list(df.columns)
44 ctx.assert_true('A' in cols and 'B' in cols, "Columns contain A and B")
45
46 # Check nrows/ncols
47 ctx.assert_equal(3, df.nrows, "nrows is 3")
48 ctx.assert_equal(2, df.ncols, "ncols is 2")
49
50 # Check len
51 ctx.assert_equal(3, len(df), "len(df) is 3")
52
53 # Check __getitem__
54 col_a = df['A']
55 ctx.assert_equal(3, len(col_a), "Column A has 3 elements")
56
57 f_print_success("DataFrame __init__ from dict: All checks passed")
shape (test_dataframe.py:40)
30def test_dataframe_init_from_dict():
31 """Test DataFrame construction from dictionary"""
32 f_print_header("Test: DataFrame __init__ from dict")
33
34 try:
35 # Create DataFrame from dict
36 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]})
37
38 # Check shape
39 ctx.assert_equal((3, 2), df.shape, "Shape is (3, 2)")
40
41 # Check columns
42 cols = list(df.columns)
43 ctx.assert_true('A' in cols and 'B' in cols, "Columns contain A and B")
44
45 # Check nrows/ncols
46 ctx.assert_equal(3, df.nrows, "nrows is 3")
47 ctx.assert_equal(2, df.ncols, "ncols is 2")
48
49 # Check len
sparse (test_sparse_accessor.py:80)
70 assert coo_obj.nnz == 2, f"Expected 2 non-zero elements"
71
72def test_dataframe_sparse_density():
73 """Test DataFrame.sparse.density"""
74 global tests_run
75 tests_run += 1
76 df = pandasCore.DataFrame({
77 "A": [0.0, 1.0, 0.0],
78 "B": [0.0, 0.0, 2.0]
79 })
80 density = df.sparse.density
81 # 2 non-zero out of 6 = 0.333...
82 assert abs(density - 0.333) < 0.01, f"Expected ~0.333, got {density}"
83
84def test_dataframe_sparse_to_dense():
85 """Test DataFrame.sparse.to_dense()"""
86 global tests_run
87 tests_run += 1
88 df = pandasCore.DataFrame({
89 "A": [0.0, 1.0, 0.0],
90 "B": [0.0, 0.0, 2.0]
__init__ (test_concat_comp.py:43)
33# ==================== concat axis=0 column union/intersection Tests ====================
34
35def test_concat_axis0_outer_union():
36 """Test concat axis=0 with join='outer' - columns from all DFs"""
37 f_print_header("concat axis=0 outer union")
38
39 pd_df1 = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
40 pd_df2 = pd.DataFrame({'B': [5, 6], 'C': [7, 8]})
41 pd_result = pd.concat([pd_df1, pd_df2], axis=0, join='outer')
42
43 pc_df1 = pandasCore.DataFrame({'A': [1, 2], 'B': [3, 4]})
44 pc_df2 = pandasCore.DataFrame({'B': [5, 6], 'C': [7, 8]})
45 pc_result = pandasCore.concat([pc_df1, pc_df2], axis=0, join='outer')
46
47 ctx.assert_equal(len(pd_result), len(pc_result), "outer union row count")
48 ctx.assert_equal(len(pd_result.columns), len(pc_result.columns), "outer union col count")
49 # Check NaN fill for missing columns
50 ctx.assert_true(pd.isna(pd_result['A'].iloc[2]), "pandas A[2] is NaN")
51
52
53def test_concat_axis0_inner():
first (test_df_sorting_reshaping.py:523)
513def test_first_last():
514 """Test first and last methods"""
515 f_print_header("Test: first / last")
516
517 try:
518 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0, 4.0, 5.0]})
519
520 # These methods are for time series with DatetimeIndex
521 try:
522 first_df = df.first('3D')
523 f_print_info(f"first('3D') shape: {first_df.shape}")
524 except Exception as e:
525 f_print_info(f"first (expected - needs DatetimeIndex): {e}")
526
527 try:
528 last_df = df.last('3D')
529 f_print_info(f"last('3D') shape: {last_df.shape}")
530 except Exception as e:
531 f_print_info(f"last (expected - needs DatetimeIndex): {e}")
get (test_dataframe.py:251)
241def test_dataframe_get():
242 """Test get() method"""
243 f_print_header("Test: DataFrame.get")
244
245 try:
246 df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]})
247
248 # Get existing column
249 col_a = df.get('A')
250 ctx.assert_true(col_a is not None, "get('A') returns value")
251 ctx.assert_equal(2, len(col_a), "get('A') has 2 elements")
252
253 # Get non-existing column with default
254 result = df.get('Z', default='not_found')
255 ctx.assert_equal('not_found', result, "get('Z') returns default")
256
257 # Get non-existing column without default
258 result_none = df.get('Z')
259 ctx.assert_true(result_none is None, "get('Z') returns None")
head (test_dataframe.py:114)
104def test_dataframe_head_tail():
105 """Test head() and tail() methods"""
106 f_print_header("Test: DataFrame.head/tail")
107
108 try:
109 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0, 4.0, 5.0]})
110
111 # Test head
112 head_df = df.head(3)
113 ctx.assert_equal(3, head_df.shape[0], "head(3) returns 3 rows")
114
115 # Test tail
116 tail_df = df.tail(2)
117 ctx.assert_equal(2, tail_df.shape[0], "tail(2) returns 2 rows")
118
119 # Test default head (5 rows)
120 head_default = df.head()
121 ctx.assert_equal(5, head_default.shape[0], "head() returns 5 rows")
idxmax (test_dataframe_phase3.py:294)
284# Index Operations Tests
285# =============================================================================
286
287def test_idxmax_idxmin():
288 """Test idxmax() and idxmin() methods"""
289 f_print_header("Test: DataFrame.idxmax/idxmin")
290
291 try:
292 df = pandasCore.DataFrame({'A': [1.0, 3.0, 2.0], 'B': [6.0, 4.0, 5.0]})
293
294 idxmax_result = df.idxmax()
295 idxmin_result = df.idxmin()
296
297 # Index of max in A is row 1, in B is row 0
298 ctx.assert_true('A' in idxmax_result, "idxmax returns column A")
299 ctx.assert_true('A' in idxmin_result, "idxmin returns column A")
300
301 f_print_success("DataFrame.idxmax/idxmin: All checks passed")
302 return True
303
304 except Exception as e:
idxmin (test_dataframe_phase3.py:295)
285# =============================================================================
286
287def test_idxmax_idxmin():
288 """Test idxmax() and idxmin() methods"""
289 f_print_header("Test: DataFrame.idxmax/idxmin")
290
291 try:
292 df = pandasCore.DataFrame({'A': [1.0, 3.0, 2.0], 'B': [6.0, 4.0, 5.0]})
293
294 idxmax_result = df.idxmax()
295 idxmin_result = df.idxmin()
296
297 # Index of max in A is row 1, in B is row 0
298 ctx.assert_true('A' in idxmax_result, "idxmax returns column A")
299 ctx.assert_true('A' in idxmin_result, "idxmin returns column A")
300
301 f_print_success("DataFrame.idxmax/idxmin: All checks passed")
302 return True
303
304 except Exception as e:
305 f_print_error(f"Exception: {e}")
last (test_df_sorting_reshaping.py:529)
519 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0, 4.0, 5.0]})
520
521 # These methods are for time series with DatetimeIndex
522 try:
523 first_df = df.first('3D')
524 f_print_info(f"first('3D') shape: {first_df.shape}")
525 except Exception as e:
526 f_print_info(f"first (expected - needs DatetimeIndex): {e}")
527
528 try:
529 last_df = df.last('3D')
530 f_print_info(f"last('3D') shape: {last_df.shape}")
531 except Exception as e:
532 f_print_info(f"last (expected - needs DatetimeIndex): {e}")
533
534 f_print_success("first/last: passed")
535 return True
536
537 except Exception as e:
538 f_print_error(f"first/last failed: {e}")
539 return False
nlargest (test_dataframe_phase3.py:505)
495 return False
496
497
498def test_nlargest_nsmallest():
499 """Test nlargest() and nsmallest() methods"""
500 f_print_header("Test: DataFrame.nlargest/nsmallest")
501
502 try:
503 df = pandasCore.DataFrame({'A': [1.0, 5.0, 3.0, 4.0, 2.0]})
504
505 largest = df.nlargest(2, 'A')
506 smallest = df.nsmallest(2, 'A')
507
508 ctx.assert_equal(2, largest.shape[0], "nlargest returns 2 rows")
509 ctx.assert_equal(2, smallest.shape[0], "nsmallest returns 2 rows")
510
511 f_print_success("DataFrame.nlargest/nsmallest: All checks passed")
512 return True
513
514 except Exception as e:
515 f_print_error(f"Exception: {e}")
nsmallest (test_dataframe_phase3.py:506)
496def test_nlargest_nsmallest():
497 """Test nlargest() and nsmallest() methods"""
498 f_print_header("Test: DataFrame.nlargest/nsmallest")
499
500 try:
501 df = pandasCore.DataFrame({'A': [1.0, 5.0, 3.0, 4.0, 2.0]})
502
503 largest = df.nlargest(2, 'A')
504 smallest = df.nsmallest(2, 'A')
505
506 ctx.assert_equal(2, largest.shape[0], "nlargest returns 2 rows")
507 ctx.assert_equal(2, smallest.shape[0], "nsmallest returns 2 rows")
508
509 f_print_success("DataFrame.nlargest/nsmallest: All checks passed")
510 return True
511
512 except Exception as e:
513 f_print_error(f"Exception: {e}")
514 return False
query (test_dataframe_phase2.py:329)
319 return False
320
321
322def test_query():
323 """Test query method"""
324 f_print_header("Test: query")
325
326 try:
327 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0, 4.0, 5.0], 'B': [5.0, 4.0, 3.0, 2.0, 1.0]})
328
329 result = df.query("A > 2")
330 ctx.assert_true(result.shape[0] < df.shape[0], "Query filters rows")
331 ctx.assert_true(result.shape[0] == 3, "Query returns 3 rows (A=3,4,5)")
332
333 f_print_success("query: All checks passed")
334 return True
335 except Exception as e:
336 f_print_error(f"Exception: {e}")
337 return False
sample (test_dataframe.py:340)
330def test_dataframe_sample():
331 """Test sample() method"""
332 f_print_header("Test: DataFrame.sample")
333
334 try:
335 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]})
336
337 # Sample by n
338 sampled = df.sample(n=3, random_state=42)
339 ctx.assert_equal(3, sampled.shape[0], "sample(n=3) returns 3 rows")
340
341 # Sample by frac
342 sampled_frac = df.sample(frac=0.5, random_state=42)
343 ctx.assert_equal(5, sampled_frac.shape[0], "sample(frac=0.5) returns 5 rows")
344
345 f_print_success("DataFrame.sample: All checks passed")
346 return True
347
348 except Exception as e:
tail (test_dataframe.py:118)
108 f_print_header("Test: DataFrame.head/tail")
109
110 try:
111 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0, 4.0, 5.0]})
112
113 # Test head
114 head_df = df.head(3)
115 ctx.assert_equal(3, head_df.shape[0], "head(3) returns 3 rows")
116
117 # Test tail
118 tail_df = df.tail(2)
119 ctx.assert_equal(2, tail_df.shape[0], "tail(2) returns 2 rows")
120
121 # Test default head (5 rows)
122 head_default = df.head()
123 ctx.assert_equal(5, head_default.shape[0], "head() returns 5 rows")
124
125 f_print_success("DataFrame.head/tail: All checks passed")
126 return True
127
128 except Exception as e:
take (test_dataframe.py:321)
311def test_dataframe_take():
312 """Test take() method"""
313 f_print_header("Test: DataFrame.take")
314
315 try:
316 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0, 4.0, 5.0]})
317
318 # Take specific indices
319 taken = df.take([0, 2, 4])
320 ctx.assert_equal(3, taken.shape[0], "take([0,2,4]) returns 3 rows")
321
322 f_print_success("DataFrame.take: All checks passed")
323 return True
324
325 except Exception as e:
326 f_print_error(f"Exception: {e}")
327 return False
where (test_signature_phase13.py:302)
292 df2 = pandasCore.DataFrame({'A': [5.0, 6.0], 'B': [7.0, 8.0]})
293 df.update(df2, join='left', overwrite=True, filter_func=None, errors='ignore')
294
295
296def test_where_signature():
297 """Test DataFrame.where has all pandas parameters."""
298 import pandasCore
299
300 df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]})
301 cond = pandasCore.DataFrame({'A': [True, False], 'B': [False, True]})
302 result = df.where(cond, other=float('nan'), inplace=False, axis=None, level=None)
303 assert isinstance(result, pandasCore.DataFrame)
304
305
306def test_xs_signature():
307 """Test DataFrame.xs has all pandas parameters."""
308 import pandasCore
309
310 df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]})
311 try:
312 result = df.xs('0', axis=0, level=None, drop_level=True)
xs (test_signature_phase13.py:312)
302 result = df.where(cond, other=float('nan'), inplace=False, axis=None, level=None)
303 assert isinstance(result, pandasCore.DataFrame)
304
305
306def test_xs_signature():
307 """Test DataFrame.xs has all pandas parameters."""
308 import pandasCore
309
310 df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]})
311 try:
312 result = df.xs('0', axis=0, level=None, drop_level=True)
313 except (RuntimeError, KeyError) as e:
314 print(f" Note: xs error (expected with non-existing key): {e}")
315
316
317def f_main():
318 """Main test function."""
319 global tests_run, tests_passed, tests_failed
320
321 f_print_header("Phase 13: DataFrame Missing Parameters Signature Tests")
assign (test_dataframe_phase2.py:370)
360 return False
361
362
363def test_assign():
364 """Test assign method"""
365 f_print_header("Test: assign")
366
367 try:
368 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]})
369
370 result = df.assign(B=[4.0, 5.0, 6.0], C=[7.0, 8.0, 9.0])
371
372 cols = list(result.columns)
373 ctx.assert_true('A' in cols, "Original column A exists")
374 ctx.assert_true('B' in cols, "New column B exists")
375 ctx.assert_true('C' in cols, "New column C exists")
376 ctx.assert_equal(3, len(cols), "Three columns after assign")
377
378 f_print_success("assign: All checks passed")
379 return True
380 except Exception as e:
drop (test_dataframe_phase2.py:103)
93def test_drop():
94 """Test drop method"""
95 f_print_header("Test: drop")
96
97 try:
98 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0], 'C': [7.0, 8.0, 9.0]})
99
100 # Drop columns
101 result = df.drop(columns=['B'])
102 cols = list(result.columns)
103 ctx.assert_equal(2, len(cols), "Two columns after drop")
104 ctx.assert_true('B' not in cols, "Column 'B' removed")
105
106 f_print_success("drop: All checks passed")
107 return True
108 except Exception as e:
109 f_print_error(f"Exception: {e}")
110 return False
droplevel (test_df_sorting_reshaping.py:108)
98def test_droplevel():
99 """Test droplevel method"""
100 f_print_header("Test: droplevel")
101
102 try:
103 df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]})
104
105 # droplevel with int (may fail if no MultiIndex)
106 try:
107 result = df.droplevel(0, axis=0)
108 f_print_info(f"droplevel result shape: {result.shape}")
109 except Exception as e:
110 f_print_info(f"droplevel (no MultiIndex): {e}")
111
112 f_print_success("droplevel: passed")
113 return True
114
115 except Exception as e:
116 f_print_error(f"droplevel failed: {e}")
117 return False
insert (test_dataframe_phase2.py:392)
382 return False
383
384
385def test_insert():
386 """Test insert method"""
387 f_print_header("Test: insert")
388
389 try:
390 df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]})
391
392 df.insert(1, 'X', [10.0, 20.0])
393 cols = list(df.columns)
394 ctx.assert_equal(3, len(cols), "Three columns after insert")
395 ctx.assert_true('X' in cols, "Column X inserted")
396
397 f_print_success("insert: All checks passed")
398 return True
399 except Exception as e:
400 f_print_error(f"Exception: {e}")
401 return False
pop (test_dataframe_phase2.py:411)
401 return False
402
403
404def test_pop():
405 """Test pop method"""
406 f_print_header("Test: pop")
407
408 try:
409 df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0], 'C': [5.0, 6.0]})
410
411 popped = df.pop('B')
412 cols = list(df.columns)
413
414 ctx.assert_equal(2, len(popped), "Popped column has 2 values")
415 ctx.assert_true('B' not in cols, "Column B removed from DataFrame")
416 ctx.assert_equal(2, len(cols), "Two columns remain")
417
418 f_print_success("pop: All checks passed")
419 return True
420 except Exception as e:
421 f_print_error(f"Exception: {e}")
reindex (test_dataframe_phase2.py:487)
477def test_reindex():
478 """Test reindex method"""
479 f_print_header("Test: reindex")
480
481 try:
482 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]})
483
484 # Reindex columns
485 result = df.reindex(['A'], axis=1)
486 ctx.assert_true(result.ncols == 1, "One column after reindex")
487
488 f_print_success("reindex: All checks passed")
489 return True
490 except Exception as e:
491 f_print_error(f"Exception: {e}")
492 return False
493
494
495def f_main():
rename (test_dataframe_phase2.py:81)
71 f_print_error(f"Exception: {e}")
72 return False
73
74
75def test_rename():
76 """Test rename method"""
77 f_print_header("Test: rename")
78
79 try:
80 df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]})
81 result = df.rename(columns={'A': 'X', 'B': 'Y'})
82
83 cols = list(result.columns)
84 ctx.assert_true('X' in cols, "Column 'X' exists after rename")
85 ctx.assert_true('Y' in cols, "Column 'Y' exists after rename")
86 ctx.assert_true('A' not in cols, "Column 'A' no longer exists")
87
88 f_print_success("rename: All checks passed")
89 return True
90 except Exception as e:
91 f_print_error(f"Exception: {e}")
rename_axis (test_dataframe_phase2.py:469)
459 return False
460
461
462def test_rename_axis():
463 """Test rename_axis method"""
464 f_print_header("Test: rename_axis")
465
466 try:
467 df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]})
468
469 result = df.rename_axis("my_axis", axis=0)
470 ctx.assert_true(result.shape == df.shape, "Shape preserved after rename_axis")
471
472 f_print_success("rename_axis: All checks passed")
473 return True
474 except Exception as e:
475 f_print_error(f"Exception: {e}")
476 return False
477
478
479def test_reindex():
reorder_levels (test_df_sorting_reshaping.py:457)
447def test_reorder_levels():
448 """Test reorder_levels method"""
449 f_print_header("Test: reorder_levels")
450
451 try:
452 df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]})
453
454 # This may fail without a proper MultiIndex
455 try:
456 reordered = df.reorder_levels([0], axis=0)
457 f_print_info(f"reorder_levels shape: {reordered.shape}")
458 except Exception as e:
459 f_print_info(f"reorder_levels (expected - no MultiIndex): {e}")
460
461 f_print_success("reorder_levels: passed")
462 return True
463
464 except Exception as e:
465 f_print_error(f"reorder_levels failed: {e}")
466 return False
replace (test_dataframe_phase2.py:288)
278 return False
279
280
281def test_replace():
282 """Test replace method"""
283 f_print_header("Test: replace")
284
285 try:
286 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [2.0, 2.0, 4.0]})
287
288 result = df.replace(2.0, 99.0)
289 # Check that 2.0 was replaced with 99.0
290 col_a = result['A']
291
292 # Column A had one 2.0 at index 1, should now have 99.0
293 ctx.assert_equal(99.0, float(col_a[1]), "2.0 replaced with 99.0 in column A")
294
295 f_print_success("replace: All checks passed")
296 return True
297 except Exception as e:
298 f_print_error(f"Exception: {e}")
set_axis (test_df_sorting_reshaping.py:84)
74def test_set_axis():
75 """Test set_axis method"""
76 f_print_header("Test: set_axis")
77
78 try:
79 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]})
80
81 # Set row labels
82 new_df = df.set_axis(['x', 'y', 'z'], axis=0)
83 f_print_info(f"set_axis row shape: {new_df.shape}")
84
85 # Set column labels
86 new_df2 = df.set_axis(['X', 'Y'], axis=1)
87 f_print_info(f"set_axis col shape: {new_df2.shape}")
88 f_print_success("set_axis: passed")
89
90 return True
91
92 except Exception as e:
set_index (test_df_phase6.py:255)
245 return False
246
247
248def test_set_index():
249 """Test set_index method"""
250 f_print_header("Test: set_index")
251
252 try:
253 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]})
254
255 result = df.set_index('A')
256 f_print_info(f"set_index shape: {result.shape}")
257 f_print_info(f"set_index columns: {list(result.columns)}")
258
259 # After set_index, we should have one less column
260 if result.shape[1] == 1: # B column only
261 f_print_success("set_index: passed")
262 else:
263 f_print_error(f"set_index: expected 1 column, got {result.shape[1]}")
264 return False
swaplevel (test_df_sorting_reshaping.py:479)
469def test_swaplevel():
470 """Test swaplevel method"""
471 f_print_header("Test: swaplevel")
472
473 try:
474 df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]})
475
476 # This may fail without a proper MultiIndex
477 try:
478 swapped = df.swaplevel(-2, -1, axis=0)
479 f_print_info(f"swaplevel shape: {swapped.shape}")
480 except Exception as e:
481 f_print_info(f"swaplevel (expected - no MultiIndex): {e}")
482
483 f_print_success("swaplevel: passed")
484 return True
485
486 except Exception as e:
487 f_print_error(f"swaplevel failed: {e}")
488 return False
update (test_signature_phase13.py:293)
283 coerce_float=False, nrows=None)
284 assert isinstance(result, pandasCore.DataFrame)
285
286
287def test_update_signature():
288 """Test DataFrame.update has all pandas parameters."""
289 import pandasCore
290
291 df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]})
292 df2 = pandasCore.DataFrame({'A': [5.0, 6.0], 'B': [7.0, 8.0]})
293 df.update(df2, join='left', overwrite=True, filter_func=None, errors='ignore')
294
295
296def test_where_signature():
297 """Test DataFrame.where has all pandas parameters."""
298 import pandasCore
299
300 df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]})
301 cond = pandasCore.DataFrame({'A': [True, False], 'B': [False, True]})
302 result = df.where(cond, other=float('nan'), inplace=False, axis=None, level=None)
303 assert isinstance(result, pandasCore.DataFrame)
backfill (test_df_phase6.py:219)
209 return False
210
211
212def test_backfill():
213 """Test backfill method"""
214 f_print_header("Test: backfill")
215
216 try:
217 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]})
218
219 result = df.backfill()
220 f_print_info(f"backfill shape: {result.shape}")
221 f_print_success("backfill: passed")
222
223 return True
224
225 except Exception as e:
226 f_print_error(f"backfill failed: {e}")
227 return False
bfill (test_dataframe_phase2.py:269)
259 return False
260
261
262def test_bfill():
263 """Test bfill method"""
264 f_print_header("Test: bfill")
265
266 try:
267 df = pandasCore.DataFrame({'A': [float('nan'), 2.0, 3.0]})
268
269 result = df.bfill()
270 # After bfill, the NaN in position [0,0] should be filled with 2.0
271 isna_result = result.isna()
272 ctx.assert_equal(False, isna_result['A'][0], "NaN filled by bfill")
273
274 f_print_success("bfill: All checks passed")
275 return True
276 except Exception as e:
277 f_print_error(f"Exception: {e}")
278 return False
dropna (test_dataframe_phase2.py:185)
175 return False
176
177
178def test_dropna():
179 """Test dropna method"""
180 f_print_header("Test: dropna")
181
182 try:
183 df = pandasCore.DataFrame({'A': [1.0, float('nan'), 3.0], 'B': [4.0, 5.0, 6.0]})
184
185 result = df.dropna()
186 # Should have fewer rows
187 ctx.assert_true(result.shape[0] < df.shape[0], "Fewer rows after dropna")
188
189 f_print_success("dropna: All checks passed")
190 return True
191 except Exception as e:
192 f_print_error(f"Exception: {e}")
193 return False
ffill (test_dataframe_phase2.py:249)
239 return False
240
241
242def test_ffill():
243 """Test ffill method"""
244 f_print_header("Test: ffill")
245
246 try:
247 df = pandasCore.DataFrame({'A': [1.0, float('nan'), 3.0], 'B': [float('nan'), 2.0, float('nan')]})
248
249 result = df.ffill()
250 # After ffill, the NaN in position [1,0] should be filled with 1.0
251 isna_result = result.isna()
252 # The first column should have no NaN after ffill (first value propagates forward)
253 ctx.assert_equal(False, isna_result['A'][1], "NaN filled by ffill")
254
255 f_print_success("ffill: All checks passed")
256 return True
257 except Exception as e:
258 f_print_error(f"Exception: {e}")
259 return False
fillna (test_dataframe_phase2.py:162)
152def test_fillna():
153 """Test fillna method"""
154 f_print_header("Test: fillna")
155
156 try:
157 df = pandasCore.DataFrame({'A': [1.0, float('nan'), 3.0], 'B': [4.0, 5.0, float('nan')]})
158
159 # Fill with scalar
160 result = df.fillna(value=0.0)
161 # Check that NaN values are replaced - access by column name
162 isna_result = result.isna()
163 # isna returns DataFrame with 1.0 for True, 0.0 for False
164 # Check that no column has any NaN (all values should be 0.0)
165 has_na_a = any(v == 1.0 for v in isna_result['A'])
166 has_na_b = any(v == 1.0 for v in isna_result['B'])
167 ctx.assert_true(not has_na_a and not has_na_b, "No NaN values after fillna")
168
169 f_print_success("fillna: All checks passed")
170 return True
interpolate (test_dataframe_phase2.py:432)
422 return False
423
424
425def test_interpolate():
426 """Test interpolate method"""
427 f_print_header("Test: interpolate")
428
429 try:
430 df = pandasCore.DataFrame({'A': [1.0, float('nan'), 3.0]})
431
432 result = df.interpolate()
433 # After linear interpolation, the NaN should be filled with 2.0
434 isna_result = result.isna()
435 ctx.assert_equal(False, isna_result['A'][1], "NaN filled by interpolate")
436
437 f_print_success("interpolate: All checks passed")
438 return True
439 except Exception as e:
440 f_print_error(f"Exception: {e}")
441 return False
isna (test_dataframe_phase2.py:204)
194def test_isna_notna():
195 """Test isna and notna methods"""
196 f_print_header("Test: isna/notna")
197
198 try:
199 df = pandasCore.DataFrame({'A': [1.0, float('nan'), 3.0], 'B': [4.0, 5.0, float('nan')]})
200
201 # Test isna
202 isna_result = df.isna()
203 ctx.assert_equal(3, len(isna_result), "isna returns 3 rows")
204 ctx.assert_equal(True, isna_result['A'][1], "NaN detected in row 1, col A")
205
206 # Test notna
207 notna_result = df.notna()
208 ctx.assert_equal(True, notna_result['A'][0], "Non-NaN detected in row 0, col A")
209 ctx.assert_equal(False, notna_result['A'][1], "NaN detected in row 1, col A (notna=False)")
210
211 f_print_success("isna/notna: All checks passed")
212 return True
isnull (test_dataframe_phase2.py:228)
218def test_isnull_notnull():
219 """Test isnull and notnull methods (aliases)"""
220 f_print_header("Test: isnull/notnull")
221
222 try:
223 df = pandasCore.DataFrame({'A': [1.0, float('nan')]})
224
225 # Test isnull (alias for isna)
226 isnull_result = df.isnull()
227 ctx.assert_equal(True, isnull_result['A'][1], "isnull detects NaN")
228
229 # Test notnull (alias for notna)
230 notnull_result = df.notnull()
231 ctx.assert_equal(True, notnull_result['A'][0], "notnull detects non-NaN")
232
233 f_print_success("isnull/notnull: All checks passed")
234 return True
235 except Exception as e:
236 f_print_error(f"Exception: {e}")
notna (test_dataframe_phase2.py:209)
199 try:
200 df = pandasCore.DataFrame({'A': [1.0, float('nan'), 3.0], 'B': [4.0, 5.0, float('nan')]})
201
202 # Test isna
203 isna_result = df.isna()
204 ctx.assert_equal(3, len(isna_result), "isna returns 3 rows")
205 ctx.assert_equal(True, isna_result['A'][1], "NaN detected in row 1, col A")
206
207 # Test notna
208 notna_result = df.notna()
209 ctx.assert_equal(True, notna_result['A'][0], "Non-NaN detected in row 0, col A")
210 ctx.assert_equal(False, notna_result['A'][1], "NaN detected in row 1, col A (notna=False)")
211
212 f_print_success("isna/notna: All checks passed")
213 return True
214 except Exception as e:
215 f_print_error(f"Exception: {e}")
216 return False
notnull (test_dataframe_phase2.py:232)
222 f_print_header("Test: isnull/notnull")
223
224 try:
225 df = pandasCore.DataFrame({'A': [1.0, float('nan')]})
226
227 # Test isnull (alias for isna)
228 isnull_result = df.isnull()
229 ctx.assert_equal(True, isnull_result['A'][1], "isnull detects NaN")
230
231 # Test notnull (alias for notna)
232 notnull_result = df.notnull()
233 ctx.assert_equal(True, notnull_result['A'][0], "notnull detects non-NaN")
234
235 f_print_success("isnull/notnull: All checks passed")
236 return True
237 except Exception as e:
238 f_print_error(f"Exception: {e}")
239 return False
240
241
242def test_ffill():
pad (test_df_phase6.py:237)
227 return False
228
229
230def test_pad():
231 """Test pad method"""
232 f_print_header("Test: pad")
233
234 try:
235 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]})
236
237 result = df.pad()
238 f_print_info(f"pad shape: {result.shape}")
239 f_print_success("pad: passed")
240
241 return True
242
243 except Exception as e:
244 f_print_error(f"pad failed: {e}")
245 return False
count (test_dataframe_phase3.py:252)
242# Count and Unique Tests
243# =============================================================================
244
245def test_count():
246 """Test count() method"""
247 f_print_header("Test: DataFrame.count")
248
249 try:
250 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]})
251
252 result = df.count()
253 ctx.assert_equal(3, result['A'], "count A = 3")
254 ctx.assert_equal(3, result['B'], "count B = 3")
255
256 f_print_success("DataFrame.count: All checks passed")
257 return True
258
259 except Exception as e:
260 f_print_error(f"Exception: {e}")
261 return False
cummax (test_dataframe_phase3.py:359)
349def test_cummin_cummax():
350 """Test cummin() and cummax() methods"""
351 f_print_header("Test: DataFrame.cummin/cummax")
352
353 try:
354 df = pandasCore.DataFrame({'A': [3.0, 1.0, 2.0]})
355
356 cummin_result = df.cummin()
357 cummax_result = df.cummax()
358
359 ctx.assert_equal((3, 1), cummin_result.shape, "cummin shape is (3, 1)")
360 ctx.assert_equal((3, 1), cummax_result.shape, "cummax shape is (3, 1)")
361
362 f_print_success("DataFrame.cummin/cummax: All checks passed")
363 return True
364
365 except Exception as e:
366 f_print_error(f"Exception: {e}")
367 return False
cummin (test_dataframe_phase3.py:358)
348 return False
349
350
351def test_cummin_cummax():
352 """Test cummin() and cummax() methods"""
353 f_print_header("Test: DataFrame.cummin/cummax")
354
355 try:
356 df = pandasCore.DataFrame({'A': [3.0, 1.0, 2.0]})
357
358 cummin_result = df.cummin()
359 cummax_result = df.cummax()
360
361 ctx.assert_equal((3, 1), cummin_result.shape, "cummin shape is (3, 1)")
362 ctx.assert_equal((3, 1), cummax_result.shape, "cummax shape is (3, 1)")
363
364 f_print_success("DataFrame.cummin/cummax: All checks passed")
365 return True
366
367 except Exception as e:
368 f_print_error(f"Exception: {e}")
cumprod (test_dataframe_phase3.py:339)
329 return False
330
331
332def test_cumprod():
333 """Test cumprod() method"""
334 f_print_header("Test: DataFrame.cumprod")
335
336 try:
337 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]})
338
339 result = df.cumprod()
340 ctx.assert_equal((3, 1), result.shape, "cumprod shape is (3, 1)")
341 # Values should be [1, 2, 6]
342
343 f_print_success("DataFrame.cumprod: All checks passed")
344 return True
345
346 except Exception as e:
347 f_print_error(f"Exception: {e}")
348 return False
cumsum (test_dataframe_phase3.py:320)
310# Cumulative Operations Tests
311# =============================================================================
312
313def test_cumsum():
314 """Test cumsum() method"""
315 f_print_header("Test: DataFrame.cumsum")
316
317 try:
318 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]})
319
320 result = df.cumsum()
321 ctx.assert_equal((3, 1), result.shape, "cumsum shape is (3, 1)")
322 # Values should be [1, 3, 6]
323
324 f_print_success("DataFrame.cumsum: All checks passed")
325 return True
326
327 except Exception as e:
328 f_print_error(f"Exception: {e}")
329 return False
describe (test_dataframe_phase3.py:653)
643# Describe and Mode Tests
644# =============================================================================
645
646def test_describe():
647 """Test describe() method"""
648 f_print_header("Test: DataFrame.describe")
649
650 try:
651 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0, 4.0, 5.0]})
652
653 result = df.describe()
654 ctx.assert_true(result.nrows > 0, "describe returns statistics")
655 ctx.assert_true(result.ncols > 0, "describe has columns")
656
657 f_print_success("DataFrame.describe: All checks passed")
658 return True
659
660 except Exception as e:
661 f_print_error(f"Exception: {e}")
662 return False
kurt (test_dataframe_phase3.py:203)
193 return False
194
195
196def test_kurt():
197 """Test kurt() and kurtosis() methods"""
198 f_print_header("Test: DataFrame.kurt/kurtosis")
199
200 try:
201 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0, 4.0, 5.0]})
202
203 kurt_result = df.kurt()
204 kurtosis_result = df.kurtosis()
205
206 # Both should be the same (kurtosis is alias)
207 ctx.assert_true('A' in kurt_result, "kurt returns column A")
208 ctx.assert_true('A' in kurtosis_result, "kurtosis returns column A")
209
210 f_print_success("DataFrame.kurt/kurtosis: All checks passed")
211 return True
212
213 except Exception as e:
kurtosis (test_dataframe_phase3.py:204)
194def test_kurt():
195 """Test kurt() and kurtosis() methods"""
196 f_print_header("Test: DataFrame.kurt/kurtosis")
197
198 try:
199 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0, 4.0, 5.0]})
200
201 kurt_result = df.kurt()
202 kurtosis_result = df.kurtosis()
203
204 # Both should be the same (kurtosis is alias)
205 ctx.assert_true('A' in kurt_result, "kurt returns column A")
206 ctx.assert_true('A' in kurtosis_result, "kurtosis returns column A")
207
208 f_print_success("DataFrame.kurt/kurtosis: All checks passed")
209 return True
210
211 except Exception as e:
212 f_print_error(f"Exception: {e}")
max (test_dataframe_phase3.py:120)
110def test_min_max():
111 """Test min() and max() methods"""
112 f_print_header("Test: DataFrame.min/max")
113
114 try:
115 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]})
116
117 min_result = df.min()
118 max_result = df.max()
119
120 ctx.assert_close(1.0, min_result['A'], "min A = 1.0")
121 ctx.assert_close(4.0, min_result['B'], "min B = 4.0")
122 ctx.assert_close(3.0, max_result['A'], "max A = 3.0")
123 ctx.assert_close(6.0, max_result['B'], "max B = 6.0")
124
125 f_print_success("DataFrame.min/max: All checks passed")
126 return True
127
128 except Exception as e:
mean (test_dataframe_phase3.py:81)
71 return False
72
73
74def test_mean():
75 """Test mean() method"""
76 f_print_header("Test: DataFrame.mean")
77
78 try:
79 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]})
80
81 result = df.mean()
82 ctx.assert_close(2.0, result['A'], "mean A = 2.0")
83 ctx.assert_close(5.0, result['B'], "mean B = 5.0")
84
85 f_print_success("DataFrame.mean: All checks passed")
86 return True
87
88 except Exception as e:
89 f_print_error(f"Exception: {e}")
90 return False
median (test_dataframe_phase3.py:100)
90 return False
91
92
93def test_median():
94 """Test median() method"""
95 f_print_header("Test: DataFrame.median")
96
97 try:
98 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]})
99
100 result = df.median()
101 ctx.assert_close(2.0, result['A'], "median A = 2.0")
102 ctx.assert_close(5.0, result['B'], "median B = 5.0")
103
104 f_print_success("DataFrame.median: All checks passed")
105 return True
106
107 except Exception as e:
108 f_print_error(f"Exception: {e}")
109 return False
min (test_dataframe_phase3.py:119)
109 return False
110
111
112def test_min_max():
113 """Test min() and max() methods"""
114 f_print_header("Test: DataFrame.min/max")
115
116 try:
117 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]})
118
119 min_result = df.min()
120 max_result = df.max()
121
122 ctx.assert_close(1.0, min_result['A'], "min A = 1.0")
123 ctx.assert_close(4.0, min_result['B'], "min B = 4.0")
124 ctx.assert_close(3.0, max_result['A'], "max A = 3.0")
125 ctx.assert_close(6.0, max_result['B'], "max B = 6.0")
126
127 f_print_success("DataFrame.min/max: All checks passed")
128 return True
mode (test_dataframe_phase3.py:672)
662 return False
663
664
665def test_mode():
666 """Test mode() method"""
667 f_print_header("Test: DataFrame.mode")
668
669 try:
670 df = pandasCore.DataFrame({'A': [1.0, 2.0, 2.0, 3.0]})
671
672 result = df.mode()
673 ctx.assert_true(result.ncols >= 1, "mode returns DataFrame")
674
675 f_print_success("DataFrame.mode: All checks passed")
676 return True
677
678 except Exception as e:
679 f_print_error(f"Exception: {e}")
680 return False
nunique (test_dataframe_phase3.py:271)
261 return False
262
263
264def test_nunique():
265 """Test nunique() method"""
266 f_print_header("Test: DataFrame.nunique")
267
268 try:
269 df = pandasCore.DataFrame({'A': [1.0, 2.0, 2.0, 3.0], 'B': [1.0, 1.0, 1.0, 2.0]})
270
271 result = df.nunique()
272 ctx.assert_equal(3, result['A'], "nunique A = 3")
273 ctx.assert_equal(2, result['B'], "nunique B = 2")
274
275 f_print_success("DataFrame.nunique: All checks passed")
276 return True
277
278 except Exception as e:
279 f_print_error(f"Exception: {e}")
280 return False
prod (test_dataframe_phase3.py:62)
52 return False
53
54
55def test_prod():
56 """Test prod() method"""
57 f_print_header("Test: DataFrame.prod")
58
59 try:
60 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [2.0, 3.0, 4.0]})
61
62 result = df.prod()
63 ctx.assert_close(6.0, result['A'], "prod A = 6.0")
64 ctx.assert_close(24.0, result['B'], "prod B = 24.0")
65
66 f_print_success("DataFrame.prod: All checks passed")
67 return True
68
69 except Exception as e:
70 f_print_error(f"Exception: {e}")
71 return False
quantile (test_dataframe_phase3.py:226)
216def test_quantile():
217 """Test quantile() method"""
218 f_print_header("Test: DataFrame.quantile")
219
220 try:
221 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0, 4.0, 5.0]})
222
223 # Median (q=0.5)
224 result = df.quantile(0.5)
225 ctx.assert_close(3.0, result['A'], "quantile 0.5 = 3.0")
226
227 # Q1 (q=0.25)
228 result_q1 = df.quantile(0.25)
229 ctx.assert_true('A' in result_q1, "quantile 0.25 returns column A")
230
231 f_print_success("DataFrame.quantile: All checks passed")
232 return True
233
234 except Exception as e:
sem (test_dataframe_phase3.py:164)
154 return False
155
156
157def test_sem():
158 """Test sem() method - standard error of mean"""
159 f_print_header("Test: DataFrame.sem")
160
161 try:
162 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]})
163
164 result = df.sem()
165 # sem = std / sqrt(n) = 1.0 / sqrt(3) ≈ 0.577
166 expected = 1.0 / math.sqrt(3)
167 ctx.assert_close(expected, result['A'], "sem A correct", tol=0.01)
168
169 f_print_success("DataFrame.sem: All checks passed")
170 return True
171
172 except Exception as e:
173 f_print_error(f"Exception: {e}")
174 return False
skew (test_dataframe_phase3.py:184)
174 return False
175
176
177def test_skew():
178 """Test skew() method"""
179 f_print_header("Test: DataFrame.skew")
180
181 try:
182 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0, 4.0, 5.0]})
183
184 result = df.skew()
185 # Symmetric distribution should have skew near 0
186 ctx.assert_close(0.0, result['A'], "skew A = 0.0", tol=0.1)
187
188 f_print_success("DataFrame.skew: All checks passed")
189 return True
190
191 except Exception as e:
192 f_print_error(f"Exception: {e}")
193 return False
std (test_dataframe_phase3.py:142)
132 return False
133
134
135def test_std_var():
136 """Test std() and var() methods"""
137 f_print_header("Test: DataFrame.std/var")
138
139 try:
140 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]})
141
142 std_result = df.std()
143 var_result = df.var()
144
145 # std of [1,2,3] with ddof=1 is 1.0
146 ctx.assert_close(1.0, std_result['A'], "std A = 1.0")
147 ctx.assert_close(1.0, var_result['A'], "var A = 1.0")
148
149 f_print_success("DataFrame.std/var: All checks passed")
150 return True
151
152 except Exception as e:
sum (test_dataframe_phase3.py:43)
33# Basic Statistics Tests
34# =============================================================================
35
36def test_sum():
37 """Test sum() method"""
38 f_print_header("Test: DataFrame.sum")
39
40 try:
41 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]})
42
43 result = df.sum()
44 ctx.assert_close(6.0, result['A'], "sum A = 6.0")
45 ctx.assert_close(15.0, result['B'], "sum B = 15.0")
46
47 f_print_success("DataFrame.sum: All checks passed")
48 return True
49
50 except Exception as e:
51 f_print_error(f"Exception: {e}")
52 return False
value_counts (test_dataframe_phase3.py:690)
680 return False
681
682
683def test_value_counts():
684 """Test value_counts() method"""
685 f_print_header("Test: DataFrame.value_counts")
686
687 try:
688 df = pandasCore.DataFrame({'A': [1.0, 2.0, 2.0, 3.0]})
689
690 result = df.value_counts()
691 ctx.assert_true(isinstance(result, dict), "value_counts returns dict")
692
693 f_print_success("DataFrame.value_counts: All checks passed")
694 return True
695
696 except Exception as e:
697 f_print_error(f"Exception: {e}")
698 return False
var (test_dataframe_phase3.py:143)
133def test_std_var():
134 """Test std() and var() methods"""
135 f_print_header("Test: DataFrame.std/var")
136
137 try:
138 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]})
139
140 std_result = df.std()
141 var_result = df.var()
142
143 # std of [1,2,3] with ddof=1 is 1.0
144 ctx.assert_close(1.0, std_result['A'], "std A = 1.0")
145 ctx.assert_close(1.0, var_result['A'], "var A = 1.0")
146
147 f_print_success("DataFrame.std/var: All checks passed")
148 return True
149
150 except Exception as e:
151 f_print_error(f"Exception: {e}")
agg (test_dataframe_phase3.py:531)
521# =============================================================================
522
523def test_agg():
524 """Test agg() method"""
525 f_print_header("Test: DataFrame.agg")
526
527 try:
528 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]})
529
530 # Single function
531 result = df.agg('sum')
532 ctx.assert_equal(1, result.shape[0], "agg('sum') returns 1 row")
533
534 # Multiple functions
535 result_multi = df.agg(['sum', 'mean'])
536 ctx.assert_equal(2, result_multi.shape[0], "agg(['sum', 'mean']) returns 2 rows")
537
538 f_print_success("DataFrame.agg: All checks passed")
539 return True
540
541 except Exception as e:
aggregate (test_dataframe_phase3.py:553)
543 return False
544
545
546def test_aggregate():
547 """Test aggregate() method (alias for agg)"""
548 f_print_header("Test: DataFrame.aggregate")
549
550 try:
551 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]})
552
553 result = df.aggregate('mean')
554 ctx.assert_equal(1, result.shape[0], "aggregate returns 1 row")
555
556 f_print_success("DataFrame.aggregate: All checks passed")
557 return True
558
559 except Exception as e:
560 f_print_error(f"Exception: {e}")
561 return False
apply (test_dataframe_phase3.py:571)
561 return False
562
563
564def test_apply():
565 """Test apply() method"""
566 f_print_header("Test: DataFrame.apply")
567
568 try:
569 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]})
570
571 result = df.apply('sum')
572 ctx.assert_equal(1, result.shape[0], "apply('sum') returns 1 row")
573
574 f_print_success("DataFrame.apply: All checks passed")
575 return True
576
577 except Exception as e:
578 f_print_error(f"Exception: {e}")
579 return False
ewm (test_df_phase6.py:177)
167def test_ewm():
168 """Test ewm method"""
169 f_print_header("Test: ewm")
170
171 try:
172 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0, 4.0, 5.0]})
173
174 # EWM mean
175 ewm = df.ewm(span=2)
176 result = ewm.mean()
177 f_print_info(f"EWM mean shape: {result.shape}")
178 f_print_success("ewm: mean passed")
179
180 # EWM with com parameter
181 ewm_com = df.ewm(com=0.5)
182 result_com = ewm_com.mean()
183 f_print_success("ewm: com parameter passed")
184
185 return True
expanding (test_df_phase6.py:153)
143def test_expanding():
144 """Test expanding method"""
145 f_print_header("Test: expanding")
146
147 try:
148 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0, 4.0, 5.0]})
149
150 # Expanding sum
151 expanding = df.expanding()
152 result = expanding.sum()
153 f_print_info(f"Expanding sum shape: {result.shape}")
154 f_print_success("expanding: sum passed")
155
156 # Expanding mean
157 result_mean = expanding.mean()
158 f_print_success("expanding: mean passed")
159
160 return True
groupby (test_df_phase6.py:93)
83 """Test groupby method"""
84 f_print_header("Test: groupby")
85
86 try:
87 df = pandasCore.DataFrame({
88 'category': [1.0, 1.0, 2.0, 2.0, 3.0],
89 'value': [10.0, 20.0, 30.0, 40.0, 50.0]
90 })
91
92 # Groupby and sum
93 grouped = df.groupby('category')
94 result = grouped.sum()
95 f_print_info(f"Grouped sum shape: {result.shape}")
96 f_print_success("groupby: sum passed")
97
98 # Groupby and mean
99 result_mean = grouped.mean()
100 f_print_info(f"Grouped mean shape: {result_mean.shape}")
101 f_print_success("groupby: mean passed")
102
103 # Test other aggregations
pipe (test_dataframe_phase3.py:708)
698 return False
699
700
701def test_pipe():
702 """Test pipe() method"""
703 f_print_header("Test: DataFrame.pipe")
704
705 try:
706 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]})
707
708 result = df.pipe('sum')
709 ctx.assert_true(result.shape[0] == 1, "pipe('sum') returns aggregation")
710
711 f_print_success("DataFrame.pipe: All checks passed")
712 return True
713
714 except Exception as e:
715 f_print_error(f"Exception: {e}")
716 return False
resample (test_df_phase6.py:436)
426def test_resample():
427 """Test resample method"""
428 f_print_header("Test: resample")
429
430 try:
431 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]})
432
433 # Note: resample requires DatetimeIndex
434 try:
435 resampled = df.resample('D')
436 f_print_info("resample object created")
437 f_print_success("resample: passed")
438 except Exception:
439 f_print_info("resample: skipped (requires DatetimeIndex)")
440
441 return True
442
443 except Exception as e:
444 f_print_error(f"resample failed: {e}")
445 return False
rolling (test_df_phase6.py:124)
114def test_rolling():
115 """Test rolling method"""
116 f_print_header("Test: rolling")
117
118 try:
119 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0, 4.0, 5.0]})
120
121 # Rolling sum
122 rolling = df.rolling(window=2)
123 result = rolling.sum()
124 f_print_info(f"Rolling sum shape: {result.shape}")
125 f_print_success("rolling: sum passed")
126
127 # Rolling mean
128 result_mean = rolling.mean()
129 f_print_success("rolling: mean passed")
130
131 # Rolling min/max
132 result_min = rolling.min()
transform (test_dataframe_phase3.py:589)
579 return False
580
581
582def test_transform():
583 """Test transform() method"""
584 f_print_header("Test: DataFrame.transform")
585
586 try:
587 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]})
588
589 result = df.transform('cumsum')
590 ctx.assert_equal(df.shape, result.shape, "transform preserves shape")
591
592 f_print_success("DataFrame.transform: All checks passed")
593 return True
594
595 except Exception as e:
596 f_print_error(f"Exception: {e}")
597 return False
add (test_dataframe_phase4.py:43)
33# =============================================================================
34
35def test_add():
36 """Test add operation"""
37 f_print_header("Test: add")
38
39 try:
40 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]})
41
42 # Scalar add
43 result = df.add(10.0)
44 col_a = result['A']
45 ctx.assert_close(11.0, col_a[0], "add scalar: A[0] = 11.0")
46 ctx.assert_close(12.0, col_a[1], "add scalar: A[1] = 12.0")
47 ctx.assert_close(13.0, col_a[2], "add scalar: A[2] = 13.0")
48
49 f_print_success("add: All tests passed")
50 return True
51
52 except Exception as e:
53 f_print_error(f"Exception: {e}")
div (test_dataframe_phase4.py:109)
99def test_div():
100 """Test div operation"""
101 f_print_header("Test: div")
102
103 try:
104 df = pandasCore.DataFrame({'A': [10.0, 20.0, 30.0], 'B': [40.0, 50.0, 60.0]})
105
106 # Scalar div
107 result = df.div(10.0)
108 col_a = result['A']
109 ctx.assert_close(1.0, col_a[0], "div scalar: A[0] = 1.0")
110 ctx.assert_close(2.0, col_a[1], "div scalar: A[1] = 2.0")
111 ctx.assert_close(3.0, col_a[2], "div scalar: A[2] = 3.0")
112
113 f_print_success("div: All tests passed")
114 return True
115
116 except Exception as e:
117 f_print_error(f"Exception: {e}")
floordiv (test_dataframe_phase4.py:151)
141def test_floordiv():
142 """Test floordiv operation"""
143 f_print_header("Test: floordiv")
144
145 try:
146 df = pandasCore.DataFrame({'A': [7.0, 17.0, 27.0], 'B': [45.0, 55.0, 65.0]})
147
148 # Scalar floordiv
149 result = df.floordiv(10.0)
150 col_a = result['A']
151 ctx.assert_close(0.0, col_a[0], "floordiv scalar: A[0] = 0.0")
152 ctx.assert_close(1.0, col_a[1], "floordiv scalar: A[1] = 1.0")
153 ctx.assert_close(2.0, col_a[2], "floordiv scalar: A[2] = 2.0")
154
155 f_print_success("floordiv: All tests passed")
156 return True
157
158 except Exception as e:
159 f_print_error(f"Exception: {e}")
mod (test_dataframe_phase4.py:173)
163def test_mod():
164 """Test mod operation"""
165 f_print_header("Test: mod")
166
167 try:
168 df = pandasCore.DataFrame({'A': [7.0, 17.0, 27.0], 'B': [45.0, 55.0, 65.0]})
169
170 # Scalar mod
171 result = df.mod(10.0)
172 col_a = result['A']
173 ctx.assert_close(7.0, col_a[0], "mod scalar: A[0] = 7.0")
174 ctx.assert_close(7.0, col_a[1], "mod scalar: A[1] = 7.0")
175 ctx.assert_close(7.0, col_a[2], "mod scalar: A[2] = 7.0")
176
177 f_print_success("mod: All tests passed")
178 return True
179
180 except Exception as e:
181 f_print_error(f"Exception: {e}")
mul (test_dataframe_phase4.py:87)
77def test_mul():
78 """Test mul operation"""
79 f_print_header("Test: mul")
80
81 try:
82 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]})
83
84 # Scalar mul
85 result = df.mul(2.0)
86 col_a = result['A']
87 ctx.assert_close(2.0, col_a[0], "mul scalar: A[0] = 2.0")
88 ctx.assert_close(4.0, col_a[1], "mul scalar: A[1] = 4.0")
89 ctx.assert_close(6.0, col_a[2], "mul scalar: A[2] = 6.0")
90
91 f_print_success("mul: All tests passed")
92 return True
93
94 except Exception as e:
95 f_print_error(f"Exception: {e}")
pow (test_dataframe_phase4.py:195)
185def test_pow():
186 """Test pow operation"""
187 f_print_header("Test: pow")
188
189 try:
190 df = pandasCore.DataFrame({'A': [2.0, 3.0, 4.0], 'B': [1.0, 2.0, 3.0]})
191
192 # Scalar pow
193 result = df.pow(2.0)
194 col_a = result['A']
195 ctx.assert_close(4.0, col_a[0], "pow scalar: A[0] = 4.0")
196 ctx.assert_close(9.0, col_a[1], "pow scalar: A[1] = 9.0")
197 ctx.assert_close(16.0, col_a[2], "pow scalar: A[2] = 16.0")
198
199 f_print_success("pow: All tests passed")
200 return True
201
202 except Exception as e:
203 f_print_error(f"Exception: {e}")
radd (test_dataframe_phase4.py:221)
211# =============================================================================
212
213def test_radd():
214 """Test radd operation"""
215 f_print_header("Test: radd")
216
217 try:
218 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]})
219
220 # Scalar radd (scalar + df)
221 result = df.radd(10.0)
222 col_a = result['A']
223 ctx.assert_close(11.0, col_a[0], "radd scalar: A[0] = 11.0")
224
225 f_print_success("radd: All tests passed")
226 return True
227
228 except Exception as e:
229 f_print_error(f"Exception: {e}")
230 return False
rdiv (test_dataframe_phase4.py:284)
274def test_rdiv():
275 """Test rdiv operation"""
276 f_print_header("Test: rdiv")
277
278 try:
279 df = pandasCore.DataFrame({'A': [2.0, 4.0, 5.0], 'B': [1.0, 2.0, 10.0]})
280
281 # Scalar rdiv (scalar / df)
282 result = df.rdiv(10.0)
283 col_a = result['A']
284 ctx.assert_close(5.0, col_a[0], "rdiv scalar: A[0] = 5.0") # 10 / 2
285 ctx.assert_close(2.5, col_a[1], "rdiv scalar: A[1] = 2.5") # 10 / 4
286 ctx.assert_close(2.0, col_a[2], "rdiv scalar: A[2] = 2.0") # 10 / 5
287
288 f_print_success("rdiv: All tests passed")
289 return True
290
291 except Exception as e:
292 f_print_error(f"Exception: {e}")
rfloordiv (test_dataframe_phase4.py:306)
296def test_rfloordiv():
297 """Test rfloordiv operation"""
298 f_print_header("Test: rfloordiv")
299
300 try:
301 df = pandasCore.DataFrame({'A': [3.0, 4.0, 5.0]})
302
303 # Scalar rfloordiv (scalar // df)
304 result = df.rfloordiv(10.0)
305 col_a = result['A']
306 ctx.assert_close(3.0, col_a[0], "rfloordiv scalar: A[0] = 3.0") # floor(10 / 3)
307 ctx.assert_close(2.0, col_a[1], "rfloordiv scalar: A[1] = 2.0") # floor(10 / 4)
308 ctx.assert_close(2.0, col_a[2], "rfloordiv scalar: A[2] = 2.0") # floor(10 / 5)
309
310 f_print_success("rfloordiv: All tests passed")
311 return True
312
313 except Exception as e:
314 f_print_error(f"Exception: {e}")
rmul (test_dataframe_phase4.py:263)
253def test_rmul():
254 """Test rmul operation"""
255 f_print_header("Test: rmul")
256
257 try:
258 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]})
259
260 # Scalar rmul (scalar * df)
261 result = df.rmul(3.0)
262 col_a = result['A']
263 ctx.assert_close(3.0, col_a[0], "rmul scalar: A[0] = 3.0")
264 ctx.assert_close(6.0, col_a[1], "rmul scalar: A[1] = 6.0")
265
266 f_print_success("rmul: All tests passed")
267 return True
268
269 except Exception as e:
270 f_print_error(f"Exception: {e}")
271 return False
rpow (test_dataframe_phase4.py:328)
318def test_rpow():
319 """Test rpow operation"""
320 f_print_header("Test: rpow")
321
322 try:
323 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]})
324
325 # Scalar rpow (scalar ** df)
326 result = df.rpow(2.0)
327 col_a = result['A']
328 ctx.assert_close(2.0, col_a[0], "rpow scalar: A[0] = 2.0") # 2**1
329 ctx.assert_close(4.0, col_a[1], "rpow scalar: A[1] = 4.0") # 2**2
330 ctx.assert_close(8.0, col_a[2], "rpow scalar: A[2] = 8.0") # 2**3
331
332 f_print_success("rpow: All tests passed")
333 return True
334
335 except Exception as e:
336 f_print_error(f"Exception: {e}")
rsub (test_dataframe_phase4.py:241)
231def test_rsub():
232 """Test rsub operation"""
233 f_print_header("Test: rsub")
234
235 try:
236 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]})
237
238 # Scalar rsub (scalar - df)
239 result = df.rsub(10.0)
240 col_a = result['A']
241 ctx.assert_close(9.0, col_a[0], "rsub scalar: A[0] = 9.0") # 10 - 1
242 ctx.assert_close(8.0, col_a[1], "rsub scalar: A[1] = 8.0") # 10 - 2
243 ctx.assert_close(7.0, col_a[2], "rsub scalar: A[2] = 7.0") # 10 - 3
244
245 f_print_success("rsub: All tests passed")
246 return True
247
248 except Exception as e:
249 f_print_error(f"Exception: {e}")
sub (test_dataframe_phase4.py:65)
55def test_sub():
56 """Test sub operation"""
57 f_print_header("Test: sub")
58
59 try:
60 df = pandasCore.DataFrame({'A': [10.0, 20.0, 30.0], 'B': [40.0, 50.0, 60.0]})
61
62 # Scalar sub
63 result = df.sub(5.0)
64 col_a = result['A']
65 ctx.assert_close(5.0, col_a[0], "sub scalar: A[0] = 5.0")
66 ctx.assert_close(15.0, col_a[1], "sub scalar: A[1] = 15.0")
67 ctx.assert_close(25.0, col_a[2], "sub scalar: A[2] = 25.0")
68
69 f_print_success("sub: All tests passed")
70 return True
71
72 except Exception as e:
73 f_print_error(f"Exception: {e}")
truediv (test_dataframe_phase4.py:131)
121def test_truediv():
122 """Test truediv operation"""
123 f_print_header("Test: truediv")
124
125 try:
126 df = pandasCore.DataFrame({'A': [10.0, 20.0, 30.0], 'B': [40.0, 50.0, 60.0]})
127
128 # Scalar truediv
129 result = df.truediv(10.0)
130 col_a = result['A']
131 ctx.assert_close(1.0, col_a[0], "truediv scalar: A[0] = 1.0")
132
133 f_print_success("truediv: All tests passed")
134 return True
135
136 except Exception as e:
137 f_print_error(f"Exception: {e}")
138 return False
eq (test_dataframe_phase4.py:531)
521# =============================================================================
522
523def test_eq():
524 """Test eq (equal) comparison"""
525 f_print_header("Test: eq")
526
527 try:
528 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [2.0, 2.0, 2.0]})
529
530 # Scalar comparison
531 result = df.eq(2.0)
532 col_a = result['A']
533 ctx.assert_close(0.0, col_a[0], "eq: A[0] != 2, result = 0")
534 ctx.assert_close(1.0, col_a[1], "eq: A[1] == 2, result = 1")
535 ctx.assert_close(0.0, col_a[2], "eq: A[2] != 2, result = 0")
536
537 f_print_success("eq: All tests passed")
538 return True
539
540 except Exception as e:
541 f_print_error(f"Exception: {e}")
ge (test_dataframe_phase4.py:641)
631def test_ge():
632 """Test ge (greater than or equal) comparison"""
633 f_print_header("Test: ge")
634
635 try:
636 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]})
637
638 # Scalar comparison
639 result = df.ge(2.0)
640 col_a = result['A']
641 ctx.assert_close(0.0, col_a[0], "ge: A[0] < 2, result = 0")
642 ctx.assert_close(1.0, col_a[1], "ge: A[1] >= 2, result = 1")
643 ctx.assert_close(1.0, col_a[2], "ge: A[2] >= 2, result = 1")
644
645 f_print_success("ge: All tests passed")
646 return True
647
648 except Exception as e:
649 f_print_error(f"Exception: {e}")
gt (test_dataframe_phase4.py:619)
609def test_gt():
610 """Test gt (greater than) comparison"""
611 f_print_header("Test: gt")
612
613 try:
614 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]})
615
616 # Scalar comparison
617 result = df.gt(2.0)
618 col_a = result['A']
619 ctx.assert_close(0.0, col_a[0], "gt: A[0] < 2, result = 0")
620 ctx.assert_close(0.0, col_a[1], "gt: A[1] == 2, result = 0")
621 ctx.assert_close(1.0, col_a[2], "gt: A[2] > 2, result = 1")
622
623 f_print_success("gt: All tests passed")
624 return True
625
626 except Exception as e:
627 f_print_error(f"Exception: {e}")
le (test_dataframe_phase4.py:597)
587def test_le():
588 """Test le (less than or equal) comparison"""
589 f_print_header("Test: le")
590
591 try:
592 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]})
593
594 # Scalar comparison
595 result = df.le(2.0)
596 col_a = result['A']
597 ctx.assert_close(1.0, col_a[0], "le: A[0] <= 2, result = 1")
598 ctx.assert_close(1.0, col_a[1], "le: A[1] <= 2, result = 1")
599 ctx.assert_close(0.0, col_a[2], "le: A[2] > 2, result = 0")
600
601 f_print_success("le: All tests passed")
602 return True
603
604 except Exception as e:
605 f_print_error(f"Exception: {e}")
lt (test_dataframe_phase4.py:575)
565def test_lt():
566 """Test lt (less than) comparison"""
567 f_print_header("Test: lt")
568
569 try:
570 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]})
571
572 # Scalar comparison
573 result = df.lt(2.0)
574 col_a = result['A']
575 ctx.assert_close(1.0, col_a[0], "lt: A[0] < 2, result = 1")
576 ctx.assert_close(0.0, col_a[1], "lt: A[1] == 2, result = 0")
577 ctx.assert_close(0.0, col_a[2], "lt: A[2] > 2, result = 0")
578
579 f_print_success("lt: All tests passed")
580 return True
581
582 except Exception as e:
583 f_print_error(f"Exception: {e}")
ne (test_dataframe_phase4.py:553)
543def test_ne():
544 """Test ne (not equal) comparison"""
545 f_print_header("Test: ne")
546
547 try:
548 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [2.0, 2.0, 2.0]})
549
550 # Scalar comparison
551 result = df.ne(2.0)
552 col_a = result['A']
553 ctx.assert_close(1.0, col_a[0], "ne: A[0] != 2, result = 1")
554 ctx.assert_close(0.0, col_a[1], "ne: A[1] == 2, result = 0")
555 ctx.assert_close(1.0, col_a[2], "ne: A[2] != 2, result = 1")
556
557 f_print_success("ne: All tests passed")
558 return True
559
560 except Exception as e:
561 f_print_error(f"Exception: {e}")
rank (test_dataframe_phase3.py:486)
476# Ranking and Selection Tests
477# =============================================================================
478
479def test_rank():
480 """Test rank() method"""
481 f_print_header("Test: DataFrame.rank")
482
483 try:
484 df = pandasCore.DataFrame({'A': [3.0, 1.0, 2.0]})
485
486 result = df.rank()
487 ctx.assert_equal((3, 1), result.shape, "rank shape is (3, 1)")
488 # Ranks should be [3, 1, 2]
489
490 f_print_success("DataFrame.rank: All checks passed")
491 return True
492
493 except Exception as e:
494 f_print_error(f"Exception: {e}")
495 return False
sort_index (test_df_sorting_reshaping.py:62)
52def test_sort_index():
53 """Test sort_index method"""
54 f_print_header("Test: sort_index")
55
56 try:
57 df = pandasCore.DataFrame({'A': [3.0, 1.0, 2.0], 'B': [6.0, 4.0, 5.0]})
58
59 # Sort by index ascending
60 sorted_df = df.sort_index()
61 f_print_info(f"Sorted shape: {sorted_df.shape}")
62
63 # Sort by index descending
64 sorted_desc = df.sort_index(ascending=False)
65 f_print_success("sort_index: passed")
66
67 return True
68
69 except Exception as e:
70 f_print_error(f"sort_index failed: {e}")
sort_values (test_df_sorting_reshaping.py:35)
25def test_sort_values():
26 """Test sort_values method"""
27 f_print_header("Test: sort_values")
28
29 try:
30 df = pandasCore.DataFrame({'A': [3.0, 1.0, 2.0], 'B': [6.0, 4.0, 5.0]})
31
32 # Sort by single column ascending
33 sorted_df = df.sort_values('A')
34 f_print_info(f"Original shape: {df.shape}")
35 f_print_info(f"Sorted shape: {sorted_df.shape}")
36
37 # Sort by single column descending
38 sorted_desc = df.sort_values('A', ascending=False)
39 f_print_success("sort_values: single column ascending/descending passed")
40
41 # Sort by list of columns
42 sorted_multi = df.sort_values(['A', 'B'])
43 f_print_success("sort_values: multiple columns passed")
explode (test_df_sorting_reshaping.py:298)
288 f_print_header("Test: explode")
289
290 try:
291 # Note: our implementation works with comma-separated strings
292 df = pandasCore.DataFrame({
293 'id': [1.0, 2.0],
294 'tags': [1.0, 2.0] # Simple values (no list support in this binding)
295 })
296
297 # This may not expand if values aren't comma-separated strings
298 exploded = df.explode('tags')
299 f_print_info(f"Exploded shape: {exploded.shape}")
300 f_print_success("explode: passed")
301
302 return True
303
304 except Exception as e:
305 f_print_error(f"explode failed: {e}")
306 return False
melt (test_df_sorting_reshaping.py:185)
175 f_print_header("Test: melt")
176
177 try:
178 df = pandasCore.DataFrame({
179 'id': [1.0, 2.0],
180 'A': [10.0, 20.0],
181 'B': [30.0, 40.0]
182 })
183
184 # Melt with id_vars
185 melted = df.melt(id_vars=['id'], value_vars=['A', 'B'])
186 f_print_info(f"Melted shape: {melted.shape}")
187
188 # Melt without id_vars
189 melted2 = df.melt()
190 f_print_info(f"Melted (no id) shape: {melted2.shape}")
191
192 f_print_success("melt: passed")
193 return True
194
195 except Exception as e:
pivot (test_df_sorting_reshaping.py:212)
202 f_print_header("Test: pivot")
203
204 try:
205 df = pandasCore.DataFrame({
206 'idx': [1.0, 1.0, 2.0, 2.0],
207 'col': [1.0, 2.0, 1.0, 2.0],
208 'val': [10.0, 20.0, 30.0, 40.0]
209 })
210
211 # Basic pivot
212 pivoted = df.pivot(index='idx', columns='col', values='val')
213 f_print_info(f"Pivoted shape: {pivoted.shape}")
214 f_print_success("pivot: passed")
215
216 return True
217
218 except Exception as e:
219 f_print_error(f"pivot failed: {e}")
220 return False
pivot_table (test_df_sorting_reshaping.py:235)
225 f_print_header("Test: pivot_table")
226
227 try:
228 df = pandasCore.DataFrame({
229 'region': [1.0, 1.0, 2.0, 2.0],
230 'product': [1.0, 2.0, 1.0, 2.0],
231 'sales': [100.0, 200.0, 150.0, 250.0]
232 })
233
234 # Basic pivot_table with mean aggregation
235 pt = df.pivot_table(values='sales', index='region', columns='product', aggfunc='mean')
236 f_print_info(f"Pivot table shape: {pt.shape}")
237
238 # Pivot table with sum
239 pt_sum = df.pivot_table(values='sales', index='region', columns='product', aggfunc='sum')
240 f_print_info(f"Pivot table (sum) shape: {pt_sum.shape}")
241
242 f_print_success("pivot_table: passed")
243 return True
244
245 except Exception as e:
squeeze (test_df_sorting_reshaping.py:316)
306 return False
307
308
309def test_squeeze():
310 """Test squeeze method"""
311 f_print_header("Test: squeeze")
312
313 try:
314 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]})
315
316 squeezed = df.squeeze()
317 f_print_info(f"Squeezed shape: {squeezed.shape}")
318 f_print_success("squeeze: passed")
319
320 return True
321
322 except Exception as e:
323 f_print_error(f"squeeze failed: {e}")
324 return False
stack (test_df_sorting_reshaping.py:257)
247 return False
248
249
250def test_stack():
251 """Test stack method"""
252 f_print_header("Test: stack")
253
254 try:
255 df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]})
256
257 stacked = df.stack()
258 f_print_info(f"Stacked shape: {stacked.shape}")
259 f_print_success("stack: passed")
260
261 return True
262
263 except Exception as e:
264 f_print_error(f"stack failed: {e}")
265 return False
swapaxes (test_df_sorting_reshaping.py:129)
119def test_swapaxes():
120 """Test swapaxes method"""
121 f_print_header("Test: swapaxes")
122
123 try:
124 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]})
125
126 # Swap axes (equivalent to transpose)
127 swapped = df.swapaxes(0, 1)
128 f_print_info(f"Original shape: {df.shape}, Swapped shape: {swapped.shape}")
129
130 # Shape should be transposed
131 if df.shape[0] == swapped.shape[1] and df.shape[1] == swapped.shape[0]:
132 f_print_success("swapaxes: passed")
133 return True
134 else:
135 f_print_error("swapaxes: shape mismatch")
136 return False
transpose (test_df_sorting_reshaping.py:153)
143def test_transpose():
144 """Test transpose and T property"""
145 f_print_header("Test: transpose / T")
146
147 try:
148 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]})
149
150 # Test transpose method
151 t1 = df.transpose()
152 f_print_info(f"transpose shape: {t1.shape}")
153
154 # Test T property
155 t2 = df.T
156 f_print_info(f"T property shape: {t2.shape}")
157
158 # Shapes should match
159 if t1.shape == t2.shape:
160 f_print_success("transpose/T: passed")
161 return True
unstack (test_df_sorting_reshaping.py:275)
265 return False
266
267
268def test_unstack():
269 """Test unstack method"""
270 f_print_header("Test: unstack")
271
272 try:
273 df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]})
274
275 unstacked = df.unstack()
276 f_print_info(f"Unstacked shape: {unstacked.shape}")
277 f_print_success("unstack: passed")
278
279 return True
280
281 except Exception as e:
282 f_print_error(f"unstack failed: {e}")
283 return False
align (test_signature_phase13.py:53)
43 return False
44
45
46def test_align_signature():
47 """Test DataFrame.align has all pandas parameters."""
48 import pandasCore
49
50 df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]})
51 df2 = pandasCore.DataFrame({'A': [5.0, 6.0], 'B': [7.0, 8.0]})
52
53 result = df.align(df2, join='outer', axis=None, level=None, copy=None,
54 fill_value=None, method=None, limit=None, fill_axis=None,
55 broadcast_axis=None)
56 assert isinstance(result, tuple), "align should return tuple"
57
58
59def test_set_axis_signature():
60 """Test DataFrame.set_axis has all pandas parameters."""
61 import pandasCore
62
63 df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]})
asfreq (test_df_phase6.py:282)
272def test_asfreq():
273 """Test asfreq method"""
274 f_print_header("Test: asfreq")
275
276 try:
277 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]})
278
279 # Note: asfreq requires DatetimeIndex, may not work with RangeIndex
280 try:
281 result = df.asfreq('D')
282 f_print_info(f"asfreq result shape: {result.shape}")
283 f_print_success("asfreq: passed")
284 except Exception:
285 f_print_info("asfreq: skipped (requires DatetimeIndex)")
286
287 return True
288
289 except Exception as e:
290 f_print_error(f"asfreq failed: {e}")
291 return False
at_time (test_df_phase6.py:392)
382def test_at_time():
383 """Test at_time method"""
384 f_print_header("Test: at_time")
385
386 try:
387 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]})
388
389 # Note: at_time requires DatetimeIndex
390 try:
391 result = df.at_time('12:00')
392 f_print_info(f"at_time result shape: {result.shape}")
393 f_print_success("at_time: passed")
394 except Exception:
395 f_print_info("at_time: skipped (requires DatetimeIndex)")
396
397 return True
398
399 except Exception as e:
400 f_print_error(f"at_time failed: {e}")
401 return False
between_time (test_df_phase6.py:414)
404def test_between_time():
405 """Test between_time method"""
406 f_print_header("Test: between_time")
407
408 try:
409 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]})
410
411 # Note: between_time requires DatetimeIndex
412 try:
413 result = df.between_time('09:00', '17:00')
414 f_print_info(f"between_time result shape: {result.shape}")
415 f_print_success("between_time: passed")
416 except Exception:
417 f_print_info("between_time: skipped (requires DatetimeIndex)")
418
419 return True
420
421 except Exception as e:
422 f_print_error(f"between_time failed: {e}")
423 return False
diff (test_dataframe_phase3.py:383)
373# Difference and Change Tests
374# =============================================================================
375
376def test_diff():
377 """Test diff() method"""
378 f_print_header("Test: DataFrame.diff")
379
380 try:
381 df = pandasCore.DataFrame({'A': [1.0, 2.0, 4.0, 7.0]})
382
383 result = df.diff()
384 ctx.assert_equal((4, 1), result.shape, "diff shape is (4, 1)")
385 # Values should be [NaN, 1, 2, 3]
386
387 f_print_success("DataFrame.diff: All checks passed")
388 return True
389
390 except Exception as e:
391 f_print_error(f"Exception: {e}")
392 return False
first_valid_index (test_df_sorting_reshaping.py:388)
378 return False
379
380
381def test_first_last_valid_index():
382 """Test first_valid_index and last_valid_index"""
383 f_print_header("Test: first_valid_index / last_valid_index")
384
385 try:
386 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]})
387
388 first = df.first_valid_index()
389 f_print_info(f"first_valid_index: {first}")
390
391 last = df.last_valid_index()
392 f_print_info(f"last_valid_index: {last}")
393
394 f_print_success("first_valid_index/last_valid_index: passed")
395 return True
396
397 except Exception as e:
398 f_print_error(f"first/last_valid_index failed: {e}")
last_valid_index (test_df_sorting_reshaping.py:391)
381def test_first_last_valid_index():
382 """Test first_valid_index and last_valid_index"""
383 f_print_header("Test: first_valid_index / last_valid_index")
384
385 try:
386 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]})
387
388 first = df.first_valid_index()
389 f_print_info(f"first_valid_index: {first}")
390
391 last = df.last_valid_index()
392 f_print_info(f"last_valid_index: {last}")
393
394 f_print_success("first_valid_index/last_valid_index: passed")
395 return True
396
397 except Exception as e:
398 f_print_error(f"first/last_valid_index failed: {e}")
399 return False
pct_change (test_dataframe_phase3.py:402)
392 return False
393
394
395def test_pct_change():
396 """Test pct_change() method"""
397 f_print_header("Test: DataFrame.pct_change")
398
399 try:
400 df = pandasCore.DataFrame({'A': [10.0, 11.0, 12.1]})
401
402 result = df.pct_change()
403 ctx.assert_equal((3, 1), result.shape, "pct_change shape is (3, 1)")
404 # Values should be [NaN, 0.1, 0.1]
405
406 f_print_success("DataFrame.pct_change: All checks passed")
407 return True
408
409 except Exception as e:
410 f_print_error(f"Exception: {e}")
411 return False
shift (test_df_sorting_reshaping.py:335)
325def test_shift():
326 """Test shift method"""
327 f_print_header("Test: shift")
328
329 try:
330 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]})
331
332 # Shift forward
333 shifted = df.shift(1)
334 f_print_info(f"Shifted (1) shape: {shifted.shape}")
335
336 # Shift backward
337 shifted_back = df.shift(-1)
338 f_print_info(f"Shifted (-1) shape: {shifted_back.shape}")
339
340 f_print_success("shift: passed")
341 return True
342
343 except Exception as e:
to_period (test_df_phase6.py:304)
294def test_to_period():
295 """Test to_period method"""
296 f_print_header("Test: to_period")
297
298 try:
299 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]})
300
301 # Note: to_period requires DatetimeIndex
302 try:
303 result = df.to_period('M')
304 f_print_info(f"to_period result shape: {result.shape}")
305 f_print_success("to_period: passed")
306 except Exception:
307 f_print_info("to_period: skipped (requires DatetimeIndex)")
308
309 return True
310
311 except Exception as e:
312 f_print_error(f"to_period failed: {e}")
313 return False
to_timestamp (test_df_phase6.py:326)
316def test_to_timestamp():
317 """Test to_timestamp method"""
318 f_print_header("Test: to_timestamp")
319
320 try:
321 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]})
322
323 # Note: to_timestamp requires PeriodIndex
324 try:
325 result = df.to_timestamp()
326 f_print_info(f"to_timestamp result shape: {result.shape}")
327 f_print_success("to_timestamp: passed")
328 except Exception:
329 f_print_info("to_timestamp: skipped (requires PeriodIndex)")
330
331 return True
332
333 except Exception as e:
334 f_print_error(f"to_timestamp failed: {e}")
335 return False
tz_convert (test_df_phase6.py:370)
360def test_tz_convert():
361 """Test tz_convert method"""
362 f_print_header("Test: tz_convert")
363
364 try:
365 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]})
366
367 # Note: tz_convert requires tz-aware DatetimeIndex
368 try:
369 result = df.tz_convert('US/Eastern')
370 f_print_info(f"tz_convert result shape: {result.shape}")
371 f_print_success("tz_convert: passed")
372 except Exception:
373 f_print_info("tz_convert: skipped (requires tz-aware DatetimeIndex)")
374
375 return True
376
377 except Exception as e:
378 f_print_error(f"tz_convert failed: {e}")
379 return False
tz_localize (test_df_phase6.py:348)
338def test_tz_localize():
339 """Test tz_localize method"""
340 f_print_header("Test: tz_localize")
341
342 try:
343 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]})
344
345 # Note: tz_localize requires DatetimeIndex
346 try:
347 result = df.tz_localize('UTC')
348 f_print_info(f"tz_localize result shape: {result.shape}")
349 f_print_success("tz_localize: passed")
350 except Exception:
351 f_print_info("tz_localize: skipped (requires DatetimeIndex)")
352
353 return True
354
355 except Exception as e:
356 f_print_error(f"tz_localize failed: {e}")
357 return False
to_csv (test_dataframe_io.py:38)
28def test_to_csv():
29 """Test to_csv method"""
30 f_print_header("Test: to_csv")
31
32 try:
33 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]})
34
35 # Test returning string (no file)
36 csv_str = df.to_csv(index=False)
37 if csv_str is not None and 'A' in csv_str and 'B' in csv_str:
38 f_print_success("to_csv returns CSV string")
39 else:
40 f_print_error(f"to_csv returned unexpected result: {csv_str}")
41 return False
42
43 # Test with index
44 csv_with_idx = df.to_csv(index=True)
45 if csv_with_idx is not None:
46 f_print_success("to_csv with index works")
to_dict (test_dataframe_io.py:197)
187def test_to_dict():
188 """Test to_dict method"""
189 f_print_header("Test: to_dict")
190
191 try:
192 df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]})
193
194 # Test default orient='dict'
195 d = df.to_dict()
196 if isinstance(d, dict) and 'A' in d and 'B' in d:
197 f_print_success(f"to_dict (orient='dict'): {d}")
198 else:
199 f_print_error(f"to_dict failed: {d}")
200 return False
201
202 # Test orient='list'
203 d_list = df.to_dict('list')
204 if isinstance(d_list, dict):
205 f_print_success(f"to_dict (orient='list'): {d_list}")
to_excel (test_excel_classes.py:13)
3# Phase 77: Python bindings for Excel classes
4
5import pandasCore
6import os
7
8def test_excel_writer_basic():
9 """Test ExcelWriter basic usage"""
10 path = "temp/test_writer.xlsx"
11 writer = pandasCore.ExcelWriter(path)
12 df = pandasCore.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
13 df.to_excel(writer, sheet_name="Data")
14 writer.close()
15 assert os.path.exists(path), "Excel file not created"
16 os.remove(path)
17
18def test_excel_writer_context():
19 """Test ExcelWriter context manager"""
20 path = "temp/test_ctx_writer.xlsx"
21 with pandasCore.ExcelWriter(path) as writer:
22 df = pandasCore.DataFrame({"X": [1, 2]})
23 df.to_excel(writer, sheet_name="Sheet1")
to_hdf (test_hdf5_store.py:91)
81 os.remove(path)
82
83def test_read_hdf():
84 """Test pandasCore.read_hdf()"""
85 global tests_run
86 tests_run += 1
87 path = "temp/test_read.h5"
88 os.makedirs("temp", exist_ok=True)
89
90 df = pandasCore.DataFrame({"A": [1, 2, 3]})
91 df.to_hdf(path, key="mykey")
92
93 df2 = pandasCore.read_hdf(path, key="mykey")
94 assert len(df2) == 3, f"Expected 3 rows, got {len(df2)}"
95
96 os.remove(path)
97
98def test_to_hdf():
99 """Test DataFrame.to_hdf()"""
100 global tests_run
101 tests_run += 1
to_html (test_dataframe_io.py:123)
113def test_to_html():
114 """Test to_html method"""
115 f_print_header("Test: to_html")
116
117 try:
118 df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]})
119
120 # Test returning string
121 html_str = df.to_html()
122 if html_str is not None and '<table' in html_str:
123 f_print_success("to_html returns HTML table string")
124 else:
125 f_print_error("to_html failed to return HTML")
126 return False
127
128 # Test with index=False
129 html_no_idx = df.to_html(index=False)
130 if html_no_idx is not None:
131 f_print_success("to_html with index=False works")
to_json (test_dataframe_io.py:93)
83def test_to_json():
84 """Test to_json method"""
85 f_print_header("Test: to_json")
86
87 try:
88 df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]})
89
90 # Test returning string
91 json_str = df.to_json()
92 if json_str is not None and isinstance(json_str, str):
93 f_print_success(f"to_json returns JSON string: {json_str[:50]}...")
94 else:
95 f_print_error("to_json failed to return string")
96 return False
97
98 # Test different orient
99 json_records = df.to_json(orient='records')
100 if json_records is not None:
101 f_print_success("to_json with orient='records' works")
to_latex (test_dataframe_io.py:153)
143def test_to_latex():
144 """Test to_latex method"""
145 f_print_header("Test: to_latex")
146
147 try:
148 df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]})
149
150 # Test returning string
151 latex_str = df.to_latex()
152 if latex_str is not None and ('tabular' in latex_str or 'begin' in latex_str):
153 f_print_success("to_latex returns LaTeX string")
154 else:
155 f_print_error(f"to_latex failed: {latex_str[:100] if latex_str else 'None'}")
156 return False
157
158 return True
159
160 except Exception as e:
161 f_print_error(f"Exception: {e}")
to_markdown (test_dataframe_io.py:175)
165def test_to_markdown():
166 """Test to_markdown method"""
167 f_print_header("Test: to_markdown")
168
169 try:
170 df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]})
171
172 # Test returning string
173 md_str = df.to_markdown()
174 if md_str is not None and '|' in md_str:
175 f_print_success("to_markdown returns Markdown table string")
176 else:
177 f_print_error(f"to_markdown failed: {md_str[:100] if md_str else 'None'}")
178 return False
179
180 return True
181
182 except Exception as e:
183 f_print_error(f"Exception: {e}")
to_numpy (test_dataframe_io.py:243)
233def test_to_numpy():
234 """Test to_numpy method"""
235 f_print_header("Test: to_numpy")
236
237 try:
238 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]})
239
240 # Test to_numpy
241 arr = df.to_numpy()
242 if isinstance(arr, np.ndarray):
243 f_print_success(f"to_numpy returns ndarray with shape {arr.shape}")
244 if arr.shape == (3, 2):
245 f_print_success("Shape is correct (3, 2)")
246 else:
247 f_print_error(f"Shape incorrect: expected (3, 2), got {arr.shape}")
248 return False
249 else:
250 f_print_error(f"to_numpy did not return ndarray: {type(arr)}")
251 return False
to_records (test_dataframe_io.py:481)
471def test_to_records():
472 """Test to_records method"""
473 f_print_header("Test: to_records")
474
475 try:
476 df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]})
477
478 # Test to_records
479 records = df.to_records()
480 if isinstance(records, list) and len(records) == 2:
481 f_print_success(f"to_records returns list of {len(records)} tuples")
482 else:
483 f_print_error(f"to_records failed: {type(records)}, {len(records) if isinstance(records, list) else 'N/A'}")
484 return False
485
486 return True
487
488 except Exception as e:
489 f_print_error(f"Exception: {e}")
to_string (test_dataframe_io.py:503)
493def test_to_string_enhanced():
494 """Test enhanced to_string method"""
495 f_print_header("Test: to_string (enhanced)")
496
497 try:
498 df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]})
499
500 # Test to_string returning string
501 s = df.to_string()
502 if s is not None and isinstance(s, str):
503 f_print_success(f"to_string returns: {s[:50]}...")
504 else:
505 f_print_error("to_string failed")
506 return False
507
508 return True
509
510 except Exception as e:
511 f_print_error(f"Exception: {e}")
to_xml (test_dataframe_io.py:270)
260def test_to_xml():
261 """Test to_xml method"""
262 f_print_header("Test: to_xml")
263
264 try:
265 df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]})
266
267 # Test returning string
268 xml_str = df.to_xml()
269 if xml_str is not None and '<?xml' in xml_str and '<data>' in xml_str:
270 f_print_success("to_xml returns XML string")
271 else:
272 f_print_error(f"to_xml failed: {xml_str[:100] if xml_str else 'None'}")
273 return False
274
275 return True
276
277 except Exception as e:
278 f_print_error(f"Exception: {e}")
astype (test_df_sorting_reshaping.py:410)
400def test_astype():
401 """Test astype method"""
402 f_print_header("Test: astype")
403
404 try:
405 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]})
406
407 # Convert to int64
408 int_df = df.astype('int64')
409 f_print_info(f"astype('int64') shape: {int_df.shape}")
410
411 # Convert to string
412 str_df = df.astype('string')
413 f_print_info(f"astype('string') shape: {str_df.shape}")
414
415 # Convert specific columns
416 mixed_df = df.astype({'A': 'int64', 'B': 'float64'})
417 f_print_info(f"astype(dict) shape: {mixed_df.shape}")
bool (test_missing_methods.py:66)
56 assert result2.size == 2, f"Expected size 2, got {result2.size}"
57
58def test_dataframe_bool():
59 """Test DataFrame.bool (deprecated)"""
60 global tests_run
61 tests_run += 1
62 df = pandasCore.DataFrame({'A': [1.0]})
63
64 with warnings.catch_warnings(record=True) as w:
65 warnings.simplefilter("always")
66 result = df.bool()
67 assert result == True, f"Expected True, got {result}"
68
69def test_series_bool_float():
70 """Test Series.bool for float Series (deprecated)"""
71 global tests_run
72 tests_run += 1
73 s = pandasCore.Series([1.0])
74
75 with warnings.catch_warnings(record=True) as w:
76 warnings.simplefilter("always")
convert_dtypes (test_df_sorting_reshaping.py:437)
427def test_convert_dtypes():
428 """Test convert_dtypes method"""
429 f_print_header("Test: convert_dtypes")
430
431 try:
432 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]})
433
434 # Convert dtypes
435 converted = df.convert_dtypes()
436 f_print_info(f"convert_dtypes shape: {converted.shape}")
437
438 f_print_success("convert_dtypes: passed")
439 return True
440
441 except Exception as e:
442 f_print_error(f"convert_dtypes failed: {e}")
443 return False
copy (test_dataframe.py:141)
131def test_dataframe_copy():
132 """Test copy() method"""
133 f_print_header("Test: DataFrame.copy")
134
135 try:
136 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]})
137
138 # Test deep copy
139 df_copy = df.copy(deep=True)
140
141 ctx.assert_equal(df.shape, df_copy.shape, "Copy has same shape")
142 ctx.assert_equal(list(df.columns), list(df_copy.columns), "Copy has same columns")
143
144 f_print_success("DataFrame.copy: All checks passed")
145 return True
146
147 except Exception as e:
148 f_print_error(f"Exception: {e}")
149 return False
infer_objects (test_df_phase6.py:201)
191 return False
192
193
194def test_infer_objects():
195 """Test infer_objects method"""
196 f_print_header("Test: infer_objects")
197
198 try:
199 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]})
200
201 result = df.infer_objects()
202 f_print_info(f"infer_objects shape: {result.shape}")
203 f_print_success("infer_objects: passed")
204
205 return True
206
207 except Exception as e:
208 f_print_error(f"infer_objects failed: {e}")
209 return False
items (test_dataframe.py:180)
170 return False
171
172
173def test_dataframe_items():
174 """Test items() method"""
175 f_print_header("Test: DataFrame.items")
176
177 try:
178 df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]})
179
180 items = df.items()
181 ctx.assert_equal(2, len(items), "items() returns 2 items")
182
183 # Check that items are tuples of (name, values)
184 for item in items:
185 ctx.assert_true(isinstance(item, tuple), "Each item is a tuple")
186 ctx.assert_true(len(item) == 2, "Each item has 2 elements")
187
188 f_print_success("DataFrame.items: All checks passed")
189 return True
iterrows (test_dataframe.py:203)
193 return False
194
195
196def test_dataframe_iterrows():
197 """Test iterrows() method"""
198 f_print_header("Test: DataFrame.iterrows")
199
200 try:
201 df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]})
202
203 rows = df.iterrows()
204 ctx.assert_equal(2, len(rows), "iterrows() returns 2 rows")
205
206 # Check structure
207 for idx, row in rows:
208 ctx.assert_true(isinstance(row, dict), "Row is a dict")
209 ctx.assert_true('A' in row and 'B' in row, "Row contains A and B")
210
211 f_print_success("DataFrame.iterrows: All checks passed")
212 return True
itertuples (test_dataframe.py:227)
217def test_dataframe_itertuples():
218 """Test itertuples() method"""
219 f_print_header("Test: DataFrame.itertuples")
220
221 try:
222 df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]})
223
224 # With index
225 tuples = df.itertuples(index=True)
226 ctx.assert_equal(2, len(tuples), "itertuples() returns 2 tuples")
227 ctx.assert_equal(3, len(tuples[0]), "Each tuple has 3 elements (index + 2 cols)")
228
229 # Without index
230 tuples_no_idx = df.itertuples(index=False)
231 ctx.assert_equal(2, len(tuples_no_idx[0]), "Without index: 2 elements")
232
233 f_print_success("DataFrame.itertuples: All checks passed")
234 return True
keys (test_dataframe.py:161)
151 return False
152
153
154def test_dataframe_keys():
155 """Test keys() method"""
156 f_print_header("Test: DataFrame.keys")
157
158 try:
159 df = pandasCore.DataFrame({'A': [1.0], 'B': [2.0], 'C': [3.0]})
160
161 keys = df.keys()
162 ctx.assert_true(len(keys) == 3, "keys() returns 3 keys")
163 ctx.assert_true('A' in keys and 'B' in keys and 'C' in keys, "keys contains A, B, C")
164
165 f_print_success("DataFrame.keys: All checks passed")
166 return True
167
168 except Exception as e:
169 f_print_error(f"Exception: {e}")
170 return False
drop_duplicates (test_dataframe_phase2.py:123)
113def test_drop_duplicates():
114 """Test drop_duplicates method"""
115 f_print_header("Test: drop_duplicates")
116
117 try:
118 df = pandasCore.DataFrame({'A': [1.0, 1.0, 2.0, 2.0], 'B': [1.0, 1.0, 2.0, 3.0]})
119
120 # Drop duplicates
121 result = df.drop_duplicates()
122 ctx.assert_true(result.shape[0] < df.shape[0], "Fewer rows after drop_duplicates")
123
124 f_print_success("drop_duplicates: All checks passed")
125 return True
126 except Exception as e:
127 f_print_error(f"Exception: {e}")
128 return False
129
130
131def test_duplicated():
duplicated (test_dataframe_phase2.py:140)
130 return False
131
132
133def test_duplicated():
134 """Test duplicated method"""
135 f_print_header("Test: duplicated")
136
137 try:
138 df = pandasCore.DataFrame({'A': [1.0, 1.0, 2.0], 'B': [1.0, 1.0, 2.0]})
139
140 dups = df.duplicated()
141 ctx.assert_equal(3, len(dups), "Duplicated returns list of length 3")
142 # First occurrence should not be marked as duplicate
143 ctx.assert_equal(False, dups[0], "First row is not duplicate")
144 # Second row is duplicate of first
145 ctx.assert_equal(True, dups[1], "Second row is duplicate")
146
147 f_print_success("duplicated: All checks passed")
148 return True
149 except Exception as e:
150 f_print_error(f"Exception: {e}")
isin (test_dataframe_phase2.py:309)
299 return False
300
301
302def test_isin():
303 """Test isin method"""
304 f_print_header("Test: isin")
305
306 try:
307 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]})
308
309 result = df.isin([1.0, 5.0])
310 # isin returns list of rows: result[row][col]
311 ctx.assert_equal(True, result[0][0], "1.0 is in values")
312 ctx.assert_equal(True, result[1][1], "5.0 is in values")
313 ctx.assert_equal(False, result[0][1], "4.0 is not in values")
314
315 f_print_success("isin: All checks passed")
316 return True
317 except Exception as e:
318 f_print_error(f"Exception: {e}")
319 return False
round (test_dataframe_phase4.py:453)
443def test_round():
444 """Test round operation"""
445 f_print_header("Test: round")
446
447 try:
448 df = pandasCore.DataFrame({'A': [1.234, 2.567, 3.891]})
449
450 # Round to 2 decimals
451 result = df.round(2)
452 col_a = result['A']
453 ctx.assert_close(1.23, col_a[0], "round(2): A[0] = 1.23")
454 ctx.assert_close(2.57, col_a[1], "round(2): A[1] = 2.57")
455 ctx.assert_close(3.89, col_a[2], "round(2): A[2] = 3.89")
456
457 # Round to 0 decimals
458 result0 = df.round(0)
459 col_a0 = result0['A']
460 ctx.assert_close(1.0, col_a0[0], "round(0): A[0] = 1.0")
461 ctx.assert_close(3.0, col_a0[1], "round(0): A[1] = 3.0")
abs (test_dataframe_phase4.py:431)
421# =============================================================================
422# Utility Methods Tests
423# =============================================================================
424
425def test_abs():
426 """Test abs operation"""
427 f_print_header("Test: abs")
428
429 try:
430 df = pandasCore.DataFrame({'A': [-1.0, 2.0, -3.0], 'B': [4.0, -5.0, 6.0]})
431 result = df.abs()
432 col_a = result['A']
433 ctx.assert_close(1.0, col_a[0], "abs: A[0] = 1.0")
434 ctx.assert_close(2.0, col_a[1], "abs: A[1] = 2.0")
435 ctx.assert_close(3.0, col_a[2], "abs: A[2] = 3.0")
436
437 f_print_success("abs: All tests passed")
438 return True
439
440 except Exception as e:
441 f_print_error(f"Exception: {e}")
add_prefix (test_dataframe_phase2.py:42)
32# =============================================================================
33# Test Functions
34# =============================================================================
35
36def test_add_prefix():
37 """Test add_prefix method"""
38 f_print_header("Test: add_prefix")
39
40 try:
41 df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]})
42 result = df.add_prefix("col_")
43
44 cols = list(result.columns)
45 ctx.assert_true('col_A' in cols, "Column 'col_A' exists")
46 ctx.assert_true('col_B' in cols, "Column 'col_B' exists")
47 ctx.assert_equal(2, len(cols), "Two columns after prefix")
48
49 f_print_success("add_prefix: All checks passed")
50 return True
51 except Exception as e:
52 f_print_error(f"Exception: {e}")
add_suffix (test_dataframe_phase2.py:62)
52 f_print_error(f"Exception: {e}")
53 return False
54
55
56def test_add_suffix():
57 """Test add_suffix method"""
58 f_print_header("Test: add_suffix")
59
60 try:
61 df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]})
62 result = df.add_suffix("_col")
63
64 cols = list(result.columns)
65 ctx.assert_true('A_col' in cols, "Column 'A_col' exists")
66 ctx.assert_true('B_col' in cols, "Column 'B_col' exists")
67
68 f_print_success("add_suffix: All checks passed")
69 return True
70 except Exception as e:
71 f_print_error(f"Exception: {e}")
72 return False
all (test_dataframe_phase3.py:611)
601# Boolean Reduction Tests
602# =============================================================================
603
604def test_all():
605 """Test all() method"""
606 f_print_header("Test: DataFrame.all")
607
608 try:
609 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [0.0, 1.0, 2.0]})
610
611 result = df.all()
612 ctx.assert_true(result['A'] == True, "all A = True (all non-zero)")
613 ctx.assert_true(result['B'] == False, "all B = False (has zero)")
614
615 f_print_success("DataFrame.all: All checks passed")
616 return True
617
618 except Exception as e:
619 f_print_error(f"Exception: {e}")
620 return False
any (test_dataframe_phase3.py:630)
620 return False
621
622
623def test_any():
624 """Test any() method"""
625 f_print_header("Test: DataFrame.any")
626
627 try:
628 df = pandasCore.DataFrame({'A': [0.0, 0.0, 0.0], 'B': [0.0, 1.0, 0.0]})
629
630 result = df.any()
631 ctx.assert_true(result['A'] == False, "any A = False (all zero)")
632 ctx.assert_true(result['B'] == True, "any B = True (has non-zero)")
633
634 f_print_success("DataFrame.any: All checks passed")
635 return True
636
637 except Exception as e:
638 f_print_error(f"Exception: {e}")
639 return False
boxplot (test_signature_phase13.py:262)
252 except RuntimeError as e:
253 assert "Not implemented" in str(e)
254
255
256def test_boxplot_signature():
257 """Test DataFrame.boxplot has all pandas parameters."""
258 import pandasCore
259
260 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]})
261 try:
262 result = df.boxplot(column=None, by=None, ax=None, fontsize=None, rot=0,
263 grid=True, figsize=None, layout=None, return_type=None, backend=None)
264 except RuntimeError as e:
265 assert "Not implemented" in str(e)
266
267
268def test_from_dict_signature():
269 """Test DataFrame.from_dict has all pandas parameters."""
270 import pandasCore
271
272 data = {'A': [1.0, 2.0], 'B': [3.0, 4.0]}
clip (test_dataframe_phase4.py:480)
470 f_print_error(f"Exception: {e}")
471 return False
472
473
474def test_clip():
475 """Test clip operation"""
476 f_print_header("Test: clip")
477
478 try:
479 df = pandasCore.DataFrame({'A': [1.0, 5.0, 10.0, 15.0, 20.0]})
480 result = df.clip(lower=5.0, upper=15.0)
481 col_a = result['A']
482
483 ctx.assert_close(5.0, col_a[0], "clip: A[0] clipped to 5.0")
484 ctx.assert_close(5.0, col_a[1], "clip: A[1] = 5.0")
485 ctx.assert_close(10.0, col_a[2], "clip: A[2] = 10.0")
486 ctx.assert_close(15.0, col_a[3], "clip: A[3] = 15.0")
487 ctx.assert_close(15.0, col_a[4], "clip: A[4] clipped to 15.0")
488
489 f_print_success("clip: All tests passed")
490 return True
corr (test_dataframe_phase3.py:425)
415# Correlation and Covariance Tests
416# =============================================================================
417
418def test_corr():
419 """Test corr() method"""
420 f_print_header("Test: DataFrame.corr")
421
422 try:
423 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [1.0, 2.0, 3.0]})
424
425 result = df.corr()
426 ctx.assert_equal((2, 2), result.shape, "corr shape is (2, 2)")
427
428 f_print_success("DataFrame.corr: All checks passed")
429 return True
430
431 except Exception as e:
432 f_print_error(f"Exception: {e}")
433 return False
cov (test_dataframe_phase3.py:443)
433 return False
434
435
436def test_cov():
437 """Test cov() method"""
438 f_print_header("Test: DataFrame.cov")
439
440 try:
441 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]})
442
443 result = df.cov()
444 ctx.assert_equal((2, 2), result.shape, "cov shape is (2, 2)")
445
446 f_print_success("DataFrame.cov: All checks passed")
447 return True
448
449 except Exception as e:
450 f_print_error(f"Exception: {e}")
451 return False
divide (test_dataframe_phase4.py:388)
378 f_print_error(f"Exception: {e}")
379 return False
380
381
382def test_divide():
383 """Test divide alias"""
384 f_print_header("Test: divide")
385
386 try:
387 df = pandasCore.DataFrame({'A': [10.0, 20.0, 30.0]})
388 result = df.divide(10.0)
389 col_a = result['A']
390 ctx.assert_close(1.0, col_a[0], "divide scalar: A[0] = 1.0")
391
392 f_print_success("divide: All tests passed")
393 return True
394
395 except Exception as e:
396 f_print_error(f"Exception: {e}")
397 return False
eval (test_dataframe_phase2.py:348)
338def test_eval():
339 """Test eval method"""
340 f_print_header("Test: eval")
341
342 try:
343 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]})
344
345 # Test expression evaluation (returns list)
346 result = df.eval("A + B")
347 ctx.assert_equal(3, len(result), "eval returns 3 values")
348 ctx.assert_close(5.0, result[0], "First value is 1+4=5")
349
350 # Test assignment (returns DataFrame)
351 df2 = df.eval("C = A + B")
352 ctx.assert_true('C' in list(df2.columns), "Column C created by eval")
353
354 f_print_success("eval: All checks passed")
355 return True
356 except Exception as e:
filter (test_df_sorting_reshaping.py:362)
352 f_print_header("Test: filter")
353
354 try:
355 df = pandasCore.DataFrame({
356 'A_col': [1.0, 2.0],
357 'B_col': [3.0, 4.0],
358 'C_data': [5.0, 6.0]
359 })
360
361 # Filter by items
362 filtered = df.filter(items=['A_col', 'B_col'])
363 f_print_info(f"Filtered (items) shape: {filtered.shape}")
364
365 # Filter by like
366 filtered_like = df.filter(like='col')
367 f_print_info(f"Filtered (like 'col') shape: {filtered_like.shape}")
368
369 # Filter by regex
370 filtered_regex = df.filter(regex='.*col')
371 f_print_info(f"Filtered (regex) shape: {filtered_regex.shape}")
hist (test_signature_phase13.py:249)
239 assert isinstance(result, str)
240
241
242def test_hist_signature():
243 """Test DataFrame.hist has all pandas parameters."""
244 import pandasCore
245
246 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]})
247 # Note: binding requires data as first positional arg
248 try:
249 result = df.hist(df, column=None, by=None, grid=True, xlabelsize=None, xrot=None,
250 ylabelsize=None, yrot=None, ax=None, sharex=False, sharey=False,
251 figsize=None, layout=None, bins=10, backend=None, legend=False)
252 except RuntimeError as e:
253 assert "Not implemented" in str(e)
254
255
256def test_boxplot_signature():
257 """Test DataFrame.boxplot has all pandas parameters."""
258 import pandasCore
info (test_dataframe.py:279)
269def test_dataframe_info():
270 """Test info() method"""
271 f_print_header("Test: DataFrame.info")
272
273 try:
274 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]})
275
276 # info() prints to stdout, so we just test it doesn't raise
277 f_print_info("Calling df.info():")
278 df.info()
279
280 f_print_success("DataFrame.info: No exceptions raised")
281 return True
282
283 except Exception as e:
284 f_print_error(f"Exception: {e}")
285 return False
memory_usage (test_dataframe.py:297)
287 return False
288
289
290def test_dataframe_memory_usage():
291 """Test memory_usage() method"""
292 f_print_header("Test: DataFrame.memory_usage")
293
294 try:
295 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]})
296
297 mem = df.memory_usage()
298 ctx.assert_true(isinstance(mem, dict), "memory_usage returns dict")
299 ctx.assert_true(len(mem) > 0, "memory_usage has entries")
300
301 # Check values are positive
302 for col, usage in mem.items():
303 ctx.assert_true(usage >= 0, f"Memory usage for {col} is non-negative")
304
305 f_print_success("DataFrame.memory_usage: All checks passed")
306 return True
multiply (test_dataframe_phase4.py:370)
360 f_print_error(f"Exception: {e}")
361 return False
362
363
364def test_multiply():
365 """Test multiply alias"""
366 f_print_header("Test: multiply")
367
368 try:
369 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]})
370 result = df.multiply(3.0)
371 col_a = result['A']
372 ctx.assert_close(3.0, col_a[0], "multiply scalar: A[0] = 3.0")
373
374 f_print_success("multiply: All tests passed")
375 return True
376
377 except Exception as e:
378 f_print_error(f"Exception: {e}")
379 return False
product (test_dataframe_phase4.py:406)
396 f_print_error(f"Exception: {e}")
397 return False
398
399
400def test_product():
401 """Test product alias for prod"""
402 f_print_header("Test: product")
403
404 try:
405 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [2.0, 3.0, 4.0]})
406 result = df.product()
407
408 # Product of column A: 1*2*3 = 6
409 # Product of column B: 2*3*4 = 24
410 ctx.assert_close(6.0, result['A'], "product: A = 6.0")
411 ctx.assert_close(24.0, result['B'], "product: B = 24.0")
412
413 f_print_success("product: All tests passed")
414 return True
415
416 except Exception as e:
select_dtypes (test_dataframe_phase2.py:452)
442def test_select_dtypes():
443 """Test select_dtypes method"""
444 f_print_header("Test: select_dtypes")
445
446 try:
447 df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]})
448
449 # Select numeric types (all columns are float64)
450 result = df.select_dtypes(include=['number'])
451 ctx.assert_true(result.ncols >= 0, "select_dtypes returns DataFrame")
452
453 f_print_success("select_dtypes: All checks passed")
454 return True
455 except Exception as e:
456 f_print_error(f"Exception: {e}")
457 return False
458
459
460def test_rename_axis():
set_flags (test_dataframe.py:383)
373def test_dataframe_set_flags():
374 """Test set_flags() method"""
375 f_print_header("Test: DataFrame.set_flags")
376
377 try:
378 df = pandasCore.DataFrame({'A': [1.0, 2.0]})
379
380 # set_flags returns a copy (placeholder implementation)
381 df_flagged = df.set_flags(allows_duplicate_labels=True)
382 ctx.assert_equal(df.shape, df_flagged.shape, "set_flags returns same shape")
383
384 f_print_success("DataFrame.set_flags: All checks passed")
385 return True
386
387 except Exception as e:
388 f_print_error(f"Exception: {e}")
389 return False
subtract (test_dataframe_phase4.py:352)
342# =============================================================================
343# Arithmetic Aliases Tests
344# =============================================================================
345
346def test_subtract():
347 """Test subtract alias"""
348 f_print_header("Test: subtract")
349
350 try:
351 df = pandasCore.DataFrame({'A': [10.0, 20.0, 30.0]})
352 result = df.subtract(5.0)
353 col_a = result['A']
354 ctx.assert_close(5.0, col_a[0], "subtract scalar: A[0] = 5.0")
355
356 f_print_success("subtract: All tests passed")
357 return True
358
359 except Exception as e:
360 f_print_error(f"Exception: {e}")
361 return False
truncate (test_df_sorting_reshaping.py:501)
491def test_truncate():
492 """Test truncate method"""
493 f_print_header("Test: truncate")
494
495 try:
496 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0, 4.0, 5.0]})
497
498 # Truncate (simplified - may not work with string indices)
499 try:
500 truncated = df.truncate(before='1', after='3')
501 f_print_info(f"truncate shape: {truncated.shape}")
502 except Exception as e:
503 f_print_info(f"truncate: {e}")
504
505 f_print_success("truncate: passed")
506 return True
507
508 except Exception as e:
509 f_print_error(f"truncate failed: {e}")
510 return False