scitex-pd 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
scitex_pd/__init__.py ADDED
@@ -0,0 +1,48 @@
1
+ #!/usr/bin/env python3
2
+ """scitex-pd — pandas helpers (force_df, melt_cols, find_pval, mv, etc) — standalone."""
3
+
4
+ __version__ = "0.1.0"
5
+
6
+ from ._find_indi import find_indi
7
+ from ._find_pval import _find_pval_col, find_pval
8
+ from ._force_df import force_df
9
+ from ._from_xyz import from_xyz
10
+ from ._get_unique import get_unique
11
+ from ._ignore_SettingWithCopyWarning import (
12
+ ignore_setting_with_copy_warning,
13
+ ignore_SettingWithCopyWarning,
14
+ )
15
+ from ._melt_cols import melt_cols
16
+ from ._merge_columns import merge_cols, merge_columns
17
+ from ._mv import mv, mv_to_first, mv_to_last
18
+ from ._replace import replace
19
+ from ._round import round
20
+ from ._slice import slice
21
+ from ._sort import sort
22
+ from ._to_numeric import to_numeric
23
+ from ._to_xy import to_xy
24
+ from ._to_xyz import to_xyz
25
+
26
+ __all__ = [
27
+ "find_indi",
28
+ "find_pval",
29
+ "_find_pval_col",
30
+ "force_df",
31
+ "from_xyz",
32
+ "get_unique",
33
+ "ignore_SettingWithCopyWarning",
34
+ "ignore_setting_with_copy_warning",
35
+ "melt_cols",
36
+ "merge_cols",
37
+ "merge_columns",
38
+ "mv",
39
+ "mv_to_first",
40
+ "mv_to_last",
41
+ "replace",
42
+ "round",
43
+ "slice",
44
+ "sort",
45
+ "to_numeric",
46
+ "to_xy",
47
+ "to_xyz",
48
+ ]
@@ -0,0 +1,125 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ # Time-stamp: "2024-11-05 08:11:05 (ywatanabe)"
4
+ # File: ./scitex_repo/src/scitex/pd/_find_indi.py
5
+
6
+ from typing import Dict, List, Union
7
+
8
+ import pandas as pd
9
+
10
+ # def find_indi(df: pd.DataFrame, conditions: Dict[str, Union[str, int, float, List]]) -> pd.Series:
11
+ # """Finds indices of rows that satisfy all given conditions in a DataFrame.
12
+
13
+ # Example
14
+ # -------
15
+ # >>> df = pd.DataFrame({'A': [1, 2, 3], 'B': ['x', 'y', 'x']})
16
+ # >>> conditions = {'A': [1, 2], 'B': 'x'}
17
+ # >>> result = find_indi(df, conditions)
18
+ # >>> print(result)
19
+ # 0 True
20
+ # 1 False
21
+ # 2 False
22
+ # dtype: bool
23
+
24
+ # Parameters
25
+ # ----------
26
+ # df : pd.DataFrame
27
+ # Input DataFrame to search in
28
+ # conditions : Dict[str, Union[str, int, float, List]]
29
+ # Dictionary of column names and their target values
30
+
31
+ # Returns
32
+ # -------
33
+ # pd.Series
34
+ # Boolean Series indicating which rows satisfy all conditions
35
+
36
+ # Raises
37
+ # ------
38
+ # KeyError
39
+ # If any column in conditions is not found in DataFrame
40
+ # """
41
+ # if not all(col in df.columns for col in conditions):
42
+ # missing_cols = [col for col in conditions if col not in df.columns]
43
+ # raise KeyError(f"Columns not found in DataFrame: {missing_cols}")
44
+
45
+ # condition_series = []
46
+ # for key, value in conditions.items():
47
+ # if isinstance(value, (list, tuple)):
48
+ # condition_series.append(df[key].isin(value))
49
+ # else:
50
+ # condition_series.append(df[key] == value)
51
+
52
+ # return pd.concat(condition_series, axis=1).all(axis=1)
53
+
54
+
55
+ def find_indi(
56
+ df: pd.DataFrame, conditions: Dict[str, Union[str, int, float, List]]
57
+ ) -> List[int]:
58
+ """Finds indices of rows that satisfy conditions, handling NaN values.
59
+
60
+ Example
61
+ -------
62
+ >>> df = pd.DataFrame({'A': [1, 2, None], 'B': ['x', 'y', 'x']})
63
+ >>> conditions = {'A': [1, None], 'B': 'x'}
64
+ >>> result = find_indi(df, conditions)
65
+
66
+ Parameters
67
+ ----------
68
+ df : pd.DataFrame
69
+ Input DataFrame
70
+ conditions : Dict[str, Union[str, int, float, List]]
71
+ Column conditions
72
+
73
+ Returns
74
+ -------
75
+ List[int]
76
+ List of integer indices of matching rows
77
+ """
78
+ if not conditions:
79
+ return []
80
+
81
+ if not all(col in df.columns for col in conditions):
82
+ missing_cols = [col for col in conditions if col not in df.columns]
83
+ raise KeyError(f"Columns not found in DataFrame: {missing_cols}")
84
+
85
+ condition_series = []
86
+ for key, value in conditions.items():
87
+ if isinstance(value, (list, tuple)):
88
+ # Handle NaN in lists
89
+ has_na = False
90
+ try:
91
+ # Check for None
92
+ if None in value:
93
+ has_na = True
94
+ # Check for pd.NA (may raise TypeError)
95
+ elif any(v is pd.NA for v in value):
96
+ has_na = True
97
+ # Check for np.nan
98
+ elif any(pd.isna(v) for v in value):
99
+ has_na = True
100
+ except (TypeError, ValueError):
101
+ # If any check fails, try alternative approach
102
+ has_na = any(
103
+ pd.isna(v) if not isinstance(v, str) else False for v in value
104
+ )
105
+
106
+ if has_na:
107
+ condition = df[key].isin(value) | df[key].isna()
108
+ else:
109
+ condition = df[key].isin(value)
110
+ else:
111
+ # Handle single NaN value
112
+ if pd.isna(value):
113
+ condition = df[key].isna()
114
+ else:
115
+ condition = df[key] == value
116
+ condition_series.append(condition)
117
+
118
+ if condition_series:
119
+ mask = pd.concat(condition_series, axis=1).all(axis=1)
120
+ return df.index[mask].tolist()
121
+ else:
122
+ return []
123
+
124
+
125
+ # EOF
@@ -0,0 +1,113 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ # Time-stamp: "2024-11-03 03:25:00 (ywatanabe)"
4
+ # File: ./scitex_repo/src/scitex/pd/_find_pval.py
5
+
6
+ #!/usr/bin/env python3
7
+ # -*- coding: utf-8 -*-
8
+ # Time-stamp: "2024-10-06 11:09:07 (ywatanabe)"
9
+ # /home/ywatanabe/proj/_scitex_repo_openhands/src/scitex/stats/_find_pval_col.py
10
+
11
+ """
12
+ Functionality:
13
+ - Identifies column name(s) in a DataFrame or keys in other data structures that correspond to p-values
14
+ Input:
15
+ - pandas DataFrame, numpy array, list, or dict
16
+ Output:
17
+ - String or list of strings representing the identified p-value column name(s) or key(s), or None if not found
18
+ Prerequisites:
19
+ - pandas, numpy libraries
20
+ """
21
+
22
+ import re
23
+ from typing import Dict, List, Optional, Union
24
+
25
+ import numpy as np
26
+ import pandas as pd
27
+
28
+
29
+ def find_pval(
30
+ data: Union[pd.DataFrame, np.ndarray, List, Dict], multiple: bool = True
31
+ ) -> Union[Optional[str], List[str]]:
32
+ """
33
+ Find p-value column name(s) or key(s) in various data structures.
34
+
35
+ Example:
36
+ --------
37
+ >>> df = pd.DataFrame({'p_value': [0.05, 0.01], 'pval': [0.1, 0.001], 'other': [1, 2]})
38
+ >>> find_pval(df)
39
+ ['p_value', 'pval']
40
+ >>> find_pval(df, multiple=False)
41
+ 'p_value'
42
+
43
+ Parameters:
44
+ -----------
45
+ data : Union[pd.DataFrame, np.ndarray, List, Dict]
46
+ Data structure to search for p-value column or key
47
+ multiple : bool, optional
48
+ If True, return all matches; if False, return only the first match (default is True)
49
+
50
+ Returns:
51
+ --------
52
+ Union[Optional[str], List[str]]
53
+ Name(s) of the column(s) or key(s) that match p-value patterns, or None if not found
54
+ """
55
+ if isinstance(data, pd.DataFrame):
56
+ return _find_pval_col(data, multiple)
57
+ elif isinstance(data, (np.ndarray, list, dict)):
58
+ return _find_pval(data, multiple)
59
+ else:
60
+ raise ValueError("Input must be a pandas DataFrame, numpy array, list, or dict")
61
+
62
+
63
+ def _find_pval(
64
+ data: Union[np.ndarray, List, Dict], multiple: bool
65
+ ) -> Union[Optional[str], List[str]]:
66
+ pattern = re.compile(r"p[-_]?val(ue)?(?!.*stars)", re.IGNORECASE)
67
+ matches = []
68
+
69
+ if isinstance(data, dict):
70
+ matches = [key for key in data.keys() if pattern.search(str(key))]
71
+ elif (
72
+ isinstance(data, (np.ndarray, list))
73
+ and len(data) > 0
74
+ and isinstance(data[0], dict)
75
+ ):
76
+ matches = [key for key in data[0].keys() if pattern.search(str(key))]
77
+
78
+ return matches if multiple else (matches[0] if matches else None)
79
+
80
+
81
+ def _find_pval_col(
82
+ df: pd.DataFrame, multiple: bool = False
83
+ ) -> Union[Optional[str], List[str]]:
84
+ """
85
+ Find p-value column name(s) in a DataFrame.
86
+
87
+ Example:
88
+ --------
89
+ >>> df = pd.DataFrame({'p_value': [0.05, 0.01], 'pval': [0.1, 0.001], 'other': [1, 2]})
90
+ >>> find_pval_col(df)
91
+ ['p_value', 'pval']
92
+ >>> find_pval_col(df, multiple=False)
93
+ 'p_value'
94
+
95
+ Parameters:
96
+ -----------
97
+ df : pd.DataFrame
98
+ DataFrame to search for p-value column(s)
99
+ multiple : bool, optional
100
+ If True, return all matches; if False, return only the first match (default is False)
101
+
102
+ Returns:
103
+ --------
104
+ Union[Optional[str], List[str]]
105
+ Name(s) of the column(s) that match p-value patterns, or None if not found
106
+ """
107
+ pattern = re.compile(r"p[-_]?val(ue)?(?!.*stars)", re.IGNORECASE)
108
+ matches = [col for col in df.columns if pattern.search(str(col))]
109
+
110
+ return matches if multiple else (matches[0] if matches else None)
111
+
112
+
113
+ # EOF
scitex_pd/_force_df.py ADDED
@@ -0,0 +1,153 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ # Timestamp: "2025-04-27 19:59:11 (ywatanabe)"
4
+ # File: /ssh:sp:/home/ywatanabe/proj/scitex_repo/src/scitex/pd/_force_df.py
5
+ # ----------------------------------------
6
+ import os
7
+
8
+ __FILE__ = "./src/scitex/pd/_force_df.py"
9
+ __DIR__ = os.path.dirname(__FILE__)
10
+ # ----------------------------------------
11
+
12
+ import numpy as np
13
+ import pandas as pd
14
+
15
+
16
+
17
+ def force_df(data, filler=np.nan):
18
+ """
19
+ Convert various data types to pandas DataFrame.
20
+
21
+ Parameters
22
+ ----------
23
+ data : various
24
+ The data to convert to DataFrame. Can be DataFrame, Series, ndarray,
25
+ list, tuple, dict, scalar value, etc.
26
+ filler : any, optional
27
+ Value to use for filling missing values, by default np.nan
28
+
29
+ Returns
30
+ -------
31
+ pd.DataFrame
32
+ Data converted to DataFrame
33
+
34
+ Examples
35
+ --------
36
+ >>> import scitex
37
+ >>> import pandas as pd
38
+ >>> import numpy as np
39
+
40
+ # DataFrame input returns the same DataFrame
41
+ >>> df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
42
+ >>> scitex.pd.force_df(df) is df
43
+ True
44
+
45
+ # Series input is converted to DataFrame
46
+ >>> series = pd.Series([1, 2, 3], name='test')
47
+ >>> scitex.pd.force_df(series)
48
+ test
49
+ 0 1
50
+ 1 2
51
+ 2 3
52
+
53
+ # NumPy array input is converted to DataFrame
54
+ >>> arr = np.array([1, 2, 3])
55
+ >>> scitex.pd.force_df(arr)
56
+ value
57
+ 0 1
58
+ 1 2
59
+ 2 3
60
+
61
+ # Scalar values are converted to single-value DataFrames
62
+ >>> scitex.pd.force_df(42)
63
+ value
64
+ 0 42
65
+
66
+ # Lists and tuples are converted to DataFrame
67
+ >>> scitex.pd.force_df([1, 2, 3])
68
+ value
69
+ 0 1
70
+ 1 2
71
+ 2 3
72
+
73
+ # Dictionaries are converted to DataFrame with appropriate handling
74
+ # of different length values
75
+ >>> data = {'A': [1, 2, 3], 'B': [4, 5]}
76
+ >>> scitex.pd.force_df(data)
77
+ A B
78
+ 0 1 4
79
+ 1 2 5
80
+ 2 3 NaN
81
+ """
82
+ # Return None as empty DataFrame
83
+ if data is None:
84
+ return pd.DataFrame()
85
+
86
+ # Return DataFrame as is
87
+ if isinstance(data, pd.DataFrame):
88
+ return data
89
+
90
+ # Convert Series to DataFrame
91
+ if isinstance(data, pd.Series):
92
+ return data.to_frame()
93
+
94
+ # Convert numpy array to DataFrame
95
+ if isinstance(data, np.ndarray):
96
+ # Handle 1D array
97
+ if data.ndim == 1:
98
+ return pd.DataFrame(data, columns=["value"])
99
+ # Handle 2D array
100
+ elif data.ndim == 2:
101
+ return pd.DataFrame(data)
102
+ # Handle higher dimensional arrays
103
+ else:
104
+ shape = data.shape
105
+ reshaped = data.reshape(shape[0], -1)
106
+ return pd.DataFrame(reshaped)
107
+
108
+ # Handle scalar values (int, float, str, etc.)
109
+ if isinstance(data, (int, float, str, bool)):
110
+ return pd.DataFrame([data], columns=["value"])
111
+
112
+ # Handle lists and tuples
113
+ if isinstance(data, (list, tuple)):
114
+ # Handle list of lists/arrays -> DataFrame
115
+ if len(data) > 0 and isinstance(data[0], (list, tuple, np.ndarray)):
116
+ return pd.DataFrame(data)
117
+ # Handle simple list/tuple -> single column DataFrame
118
+ else:
119
+ return pd.DataFrame(data, columns=["value"])
120
+
121
+ # Continue with the original implementation for dictionaries
122
+ if isinstance(data, dict):
123
+ # Original implementation
124
+ permutable_dict = data.copy()
125
+
126
+ # Get the lengths
127
+ max_len = 0
128
+ for k, v in permutable_dict.items():
129
+ # Check if v is an iterable (but not string) or treat as single length otherwise
130
+ if isinstance(v, (str, int, float)) or not hasattr(v, "__len__"):
131
+ length = 1
132
+ else:
133
+ length = len(v)
134
+ max_len = max(max_len, length)
135
+
136
+ # Replace with appropriately filled list
137
+ for k, v in permutable_dict.items():
138
+ if isinstance(v, (str, int, float)) or not hasattr(v, "__len__"):
139
+ permutable_dict[k] = [v] + [filler] * (max_len - 1)
140
+ else:
141
+ permutable_dict[k] = list(v) + [filler] * (max_len - len(v))
142
+
143
+ # Puts them into a DataFrame
144
+ return pd.DataFrame(permutable_dict)
145
+
146
+ # For any other iterable type
147
+ try:
148
+ return pd.DataFrame(list(data), columns=["value"])
149
+ except:
150
+ raise TypeError(f"Cannot convert object of type {type(data)} to DataFrame")
151
+
152
+
153
+ # EOF
scitex_pd/_from_xyz.py ADDED
@@ -0,0 +1,71 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ # Time-stamp: "2024-09-26 07:22:18 (ywatanabe)"
4
+ # /home/ywatanabe/proj/_scitex_repo_openhands/src/scitex/pd/_from_xyz.py
5
+
6
+ import numpy as np
7
+ import pandas as pd
8
+
9
+
10
+ def from_xyz(data_frame, x=None, y=None, z=None, square=False):
11
+ """
12
+ Convert a DataFrame with 'x', 'y', 'z' format into a heatmap DataFrame.
13
+
14
+ Example
15
+ -------
16
+ import pandas as pd
17
+ data = pd.DataFrame({
18
+ 'col1': ['A', 'B', 'C', 'A'],
19
+ 'col2': ['X', 'Y', 'Z', 'Y'],
20
+ 'p_val': [0.01, 0.05, 0.001, 0.1]
21
+ })
22
+ data = data.rename(columns={"col1": "x", "col2": "y", "p_val": "z"})
23
+ result = from_xyz(data)
24
+ print(result)
25
+
26
+ Parameters
27
+ ----------
28
+ data_frame : pandas.DataFrame
29
+ Input DataFrame with columns for x, y, and z values.
30
+ x : str, optional
31
+ Name of the column to use as x-axis. Defaults to 'x'.
32
+ y : str, optional
33
+ Name of the column to use as y-axis. Defaults to 'y'.
34
+ z : str, optional
35
+ Name of the column to use as z-values. Defaults to 'z'.
36
+ square : bool, optional
37
+ If True, force the output to be a square matrix. Defaults to False.
38
+
39
+ Returns
40
+ -------
41
+ pandas.DataFrame
42
+ A DataFrame in heatmap/pivot format.
43
+ """
44
+ x = x or "x"
45
+ y = y or "y"
46
+ z = z or "z"
47
+
48
+ heatmap = pd.pivot_table(data_frame, values=z, index=y, columns=x, aggfunc="first")
49
+
50
+ if square:
51
+ # Make it square by including all unique labels
52
+ all_labels = sorted(set(heatmap.index) | set(heatmap.columns))
53
+ heatmap = heatmap.reindex(index=all_labels, columns=all_labels)
54
+
55
+ heatmap = heatmap.fillna(0)
56
+
57
+ return heatmap
58
+
59
+
60
+ if __name__ == "__main__":
61
+ np.random.seed(42)
62
+ stats = pd.DataFrame(
63
+ {
64
+ "col1": np.random.choice(["A", "B", "C"], 100),
65
+ "col2": np.random.choice(["X", "Y", "Z"], 100),
66
+ "p_val": np.random.rand(100),
67
+ }
68
+ )
69
+ stats = stats.rename(columns={"col1": "x", "col2": "y", "p_val": "z"})
70
+ result = from_xyz(stats)
71
+ print(result)
@@ -0,0 +1,101 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ # Timestamp: "2025-09-18 18:42:11 (ywatanabe)"
4
+ # File: /ssh:sp:/home/ywatanabe/proj/scitex_repo/src/scitex/pd/_get_unique.py
5
+ # ----------------------------------------
6
+ from __future__ import annotations
7
+
8
+ import os
9
+
10
+ __FILE__ = __file__
11
+ __DIR__ = os.path.dirname(__FILE__)
12
+ # ----------------------------------------
13
+
14
+ """
15
+ Extract unique values from DataFrame columns.
16
+ """
17
+
18
+ from typing import Any, Optional
19
+
20
+ import pandas as pd
21
+
22
+
23
+ def get_unique(
24
+ df: pd.DataFrame,
25
+ column: str,
26
+ default: Optional[Any] = None,
27
+ raise_on_multiple: bool = False,
28
+ ) -> Any:
29
+ """Get value from column if it contains a unique value.
30
+
31
+ Args:
32
+ df: DataFrame to extract from
33
+ column: Column name to check
34
+ default: Default value if column doesn't exist or has multiple unique values
35
+ raise_on_multiple: If True, raise ValueError when multiple unique values exist
36
+
37
+ Returns:
38
+ The unique value if exactly one exists, otherwise default value
39
+
40
+ Examples:
41
+ >>> import pandas as pd
42
+ >>> df = pd.DataFrame({'patient_id': ['P01', 'P01', 'P01']})
43
+ >>> get_unique(df, 'patient_id')
44
+ 'P01'
45
+
46
+ >>> df = pd.DataFrame({'patient_id': ['P01', 'P02']})
47
+ >>> get_unique(df, 'patient_id', default='Unknown')
48
+ 'Unknown'
49
+
50
+ >>> # Raise error on multiple values
51
+ >>> get_unique(df, 'patient_id', raise_on_multiple=True)
52
+ ValueError: Column 'patient_id' has 2 unique values: ['P01', 'P02']
53
+ """
54
+ if column not in df.columns:
55
+ if raise_on_multiple:
56
+ raise KeyError(f"Column '{column}' not found in DataFrame")
57
+ return default
58
+
59
+ unique_values = df[column].unique()
60
+
61
+ if len(unique_values) == 1:
62
+ return unique_values[0]
63
+
64
+ if len(unique_values) > 1 and raise_on_multiple:
65
+ raise ValueError(
66
+ f"Column '{column}' has {len(unique_values)} unique values: "
67
+ f"{list(unique_values[:5])}"
68
+ )
69
+
70
+ return default
71
+
72
+
73
+ if __name__ == "__main__":
74
+ # Test the function
75
+ import pandas as pd
76
+
77
+ # Test case 1: Unique value
78
+ df1 = pd.DataFrame({"patient_id": ["P01", "P01", "P01"]})
79
+ assert get_unique(df1, "patient_id") == "P01"
80
+ print("✓ Test 1 passed: Unique value extracted")
81
+
82
+ # Test case 2: Multiple values with default
83
+ df2 = pd.DataFrame({"patient_id": ["P01", "P02"]})
84
+ assert get_unique(df2, "patient_id", default="Unknown") == "Unknown"
85
+ print("✓ Test 2 passed: Default returned for multiple values")
86
+
87
+ # Test case 3: Missing column
88
+ assert get_unique(df1, "missing_col", default="N/A") == "N/A"
89
+ print("✓ Test 3 passed: Default returned for missing column")
90
+
91
+ # Test case 4: Raise on multiple
92
+ try:
93
+ get_unique(df2, "patient_id", raise_on_multiple=True)
94
+ assert False, "Should have raised ValueError"
95
+ except ValueError as e:
96
+ assert "has 2 unique values" in str(e)
97
+ print("✓ Test 4 passed: ValueError raised for multiple values")
98
+
99
+ print("\nAll tests passed!")
100
+
101
+ # EOF
@@ -0,0 +1,34 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ # Time-stamp: "2024-11-05 07:35:30 (ywatanabe)"
4
+ # File: ./scitex_repo/src/scitex/pd/_ignore_.py
5
+
6
+ import warnings
7
+ from contextlib import contextmanager
8
+
9
+
10
+ @contextmanager
11
+ def ignore_setting_with_copy_warning():
12
+ """
13
+ Context manager to temporarily ignore pandas SettingWithCopyWarning.
14
+
15
+ Example
16
+ -------
17
+ >>> with ignore_SettingWithCopyWarning():
18
+ ... df['column'] = new_values # No warning will be shown
19
+ """
20
+ try:
21
+ from pandas.errors import SettingWithCopyWarning
22
+ except ImportError:
23
+ from pandas.core.common import SettingWithCopyWarning
24
+
25
+ # Save current warning filters
26
+ with warnings.catch_warnings():
27
+ warnings.simplefilter(action="ignore", category=SettingWithCopyWarning)
28
+ yield
29
+
30
+
31
+ # Backward compatibility
32
+ ignore_SettingWithCopyWarning = ignore_setting_with_copy_warning # Deprecated
33
+
34
+ # EOF