Skip to content

Commit 8bb264c

Browse files
create csv handler that uses similar logic to yaml_from_file
1 parent 0276cd8 commit 8bb264c

1 file changed

Lines changed: 45 additions & 0 deletions

File tree

schimpy/util/yaml_load.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,50 @@
11
from schimpy.schism_yaml import load, dump
22
from pathlib import Path
3+
import pandas as pd
4+
import string
5+
6+
7+
def csv_from_file(filename, envvar=None, **kwargs):
8+
"""
9+
Load a CSV file and substitute environment variables in string fields.
10+
11+
Parameters
12+
----------
13+
filename : str
14+
Path to the CSV file.
15+
envvar : dict, optional
16+
Dictionary of variables to substitute (e.g., {'calsim_dss': 'blah.dss'}).
17+
kwargs : passed to pd.read_csv
18+
19+
Returns
20+
-------
21+
pd.DataFrame
22+
DataFrame with substitutions applied.
23+
"""
24+
df = pd.read_csv(filename, **kwargs)
25+
if envvar is None:
26+
return df
27+
28+
# Substitute in column names
29+
df.columns = [
30+
string.Template(str(col)).safe_substitute(**envvar) for col in df.columns
31+
]
32+
33+
# Substitute in index (if it's string/object)
34+
if df.index.dtype == "object":
35+
df.index = [
36+
string.Template(str(idx)).safe_substitute(**envvar) for idx in df.index
37+
]
38+
39+
# Substitute in all string/object cells
40+
for col in df.select_dtypes(include=["object"]).columns:
41+
df[col] = (
42+
df[col]
43+
.astype(str)
44+
.apply(lambda x: string.Template(x).safe_substitute(**envvar))
45+
)
46+
47+
return df
348

449

550
def yaml_from_file(filename, envvar=None):

0 commit comments

Comments
 (0)