-
Notifications
You must be signed in to change notification settings - Fork 219
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
GMT_DATASET.to_dataframe: Return an empty DataFrame if a file contains no data #3131
Merged
Merged
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
175ba3c
GMT_DATASET: Return an empty DataFrame if the file has no data
seisman 2e6e277
Apply suggestions from code review
seisman 7482b25
Merge branch 'main' into dataset/empty_dataframe
seisman 3246e5c
Merge branch 'main' into dataset/empty_dataframe
seisman ec59f9c
Merge branch 'main' into dataset/empty_dataframe
seisman a2c48d5
Fixes
seisman 1281ec0
Add more comments
seisman b817e91
Merge branch 'main' into dataset/empty_dataframe
seisman 71cc9b7
Return an empty DataFrame with column names
seisman 065ec12
Do not assign column names again for empty DataFrame
seisman dbfc2ae
Improve type hints
seisman 06790e2
Apply suggestions from code review
seisman File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,83 @@ | ||
""" | ||
Tests for GMT_DATASET data type. | ||
""" | ||
|
||
from pathlib import Path | ||
|
||
import pandas as pd | ||
import pytest | ||
from pygmt.clib import Session | ||
from pygmt.helpers import GMTTempFile | ||
|
||
|
||
def dataframe_from_pandas(filepath_or_buffer, sep=r"\s+", comment="#", header=None): | ||
""" | ||
Read tabular data as pandas.DataFrame object using pandas.read_csv(). | ||
|
||
The parameters have the same meaning as in ``pandas.read_csv()``. | ||
""" | ||
try: | ||
df = pd.read_csv(filepath_or_buffer, sep=sep, comment=comment, header=header) | ||
except pd.errors.EmptyDataError: | ||
# Return an empty DataFrame if the file contains no data | ||
return pd.DataFrame() | ||
|
||
# By default, pandas reads text strings with whitespaces as multiple columns, but | ||
# GMT concatenates all trailing text as a single string column. Need do find all | ||
# string columns (with dtype="object") and combine them into a single string column. | ||
string_columns = df.select_dtypes(include=["object"]).columns | ||
if len(string_columns) > 1: | ||
df[string_columns[0]] = df[string_columns].apply(lambda x: " ".join(x), axis=1) | ||
df = df.drop(string_columns[1:], axis=1) | ||
# Convert 'object' to 'string' type | ||
df = df.convert_dtypes( | ||
convert_string=True, | ||
convert_integer=False, | ||
convert_boolean=False, | ||
convert_floating=False, | ||
) | ||
return df | ||
|
||
|
||
def dataframe_from_gmt(fname): | ||
""" | ||
Read tabular data as pandas.DataFrame using GMT virtual file. | ||
""" | ||
with Session() as lib: | ||
with lib.virtualfile_out(kind="dataset") as vouttbl: | ||
lib.call_module("read", f"{fname} {vouttbl} -Td") | ||
df = lib.virtualfile_to_dataset(vfname=vouttbl) | ||
return df | ||
|
||
|
||
@pytest.mark.benchmark | ||
def test_dataset(): | ||
""" | ||
Test the basic functionality of GMT_DATASET. | ||
""" | ||
with GMTTempFile(suffix=".txt") as tmpfile: | ||
with Path(tmpfile.name).open(mode="w") as fp: | ||
print(">", file=fp) | ||
print("1.0 2.0 3.0 TEXT1 TEXT23", file=fp) | ||
print("4.0 5.0 6.0 TEXT4 TEXT567", file=fp) | ||
print(">", file=fp) | ||
print("7.0 8.0 9.0 TEXT8 TEXT90", file=fp) | ||
print("10.0 11.0 12.0 TEXT123 TEXT456789", file=fp) | ||
|
||
df = dataframe_from_gmt(tmpfile.name) | ||
expected_df = dataframe_from_pandas(tmpfile.name, comment=">") | ||
pd.testing.assert_frame_equal(df, expected_df) | ||
|
||
|
||
def test_dataset_empty(): | ||
""" | ||
Make sure that an empty DataFrame is returned if a file contains no data. | ||
""" | ||
with GMTTempFile(suffix=".txt") as tmpfile: | ||
with Path(tmpfile.name).open(mode="w") as fp: | ||
print("# This is a comment line.", file=fp) | ||
|
||
df = dataframe_from_gmt(tmpfile.name) | ||
assert df.empty # Empty DataFrame | ||
expected_df = dataframe_from_pandas(tmpfile.name) | ||
pd.testing.assert_frame_equal(df, expected_df) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
For reference, GMT provides two special/undocumented modules
read
andwrite
(their source codes aregmt/src/gmtread.c
/gmt/src/gmtwrite.c
) that can read a file into a GMT object (e.g, reading a tabular file as GMT_DATASET, or reading a grid as GMT_GRID). Currently, we're frequently using the specialread
module in the doctest of thepygmt.clib.session
module (similar to lines 46-50 below). We may want to make it public in the future as already done in GMT.jl (https://www.generic-mapping-tools.org/GMT.jl/dev/#GMT.gmtread-Tuple{String} and https://www.generic-mapping-tools.org/GMT.jl/dev/#GMT.gmtwrite).