Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,7 @@
* (Java) Fixed JmsIO leaving most messages unacknowledged, and so redelivered, on runners that execute unbounded sources as splittable DoFns, such as Dataflow Runner v2. Reporting progress for an unbounded source no longer takes a checkpoint, and finalizing a JmsIO checkpoint, or resuming from it, also acknowledges the earlier checkpoints of the same reader ([#41013](https://github.com/apache/beam/pull/41013)).
* (Python) Fixed the DataFrame API `idxmin()` and `idxmax()` failing with `ValueError` when a partition is empty, for example after a filter, or when a datetime column has only `NaT` in a partition ([#41662](https://github.com/apache/beam/issues/41662)).
* (Python) Fixed local file patterns that use `/`, such as `data/*.txt`, matching no files on Windows: `ReadFromText` raised "No files found", and `ReadAllFromText` and `fileio.MatchFiles` returned nothing ([#41618](https://github.com/apache/beam/issues/41618)).
* (Python) Fixed `WriteToCsv` and `WriteToJson` ignoring `num_shards` when the input arrives as a single DataFrame batch, so they wrote one file instead of `num_shards` ([#41702](https://github.com/apache/beam/issues/41702)).

## Security Fixes

Expand Down
13 changes: 13 additions & 0 deletions sdks/python/apache_beam/dataframe/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -687,6 +687,14 @@ def process(
tracker.try_claim(tracker.current_restriction().stop)


def _split_for_shards(df, num_shards):
n = len(df)
for i in range(num_shards):
piece = df.iloc[i * n // num_shards:(i + 1) * n // num_shards]
if len(piece):
yield piece


class _WriteToPandas(beam.PTransform):
def __init__(
self, writer, path, args, kwargs, incremental=False, binary=True):
Expand All @@ -709,6 +717,11 @@ def expand(self, pcoll):
if num_shards is not None:
write_to_files_kwargs['shards'] = num_shards
write_to_files_kwargs['max_writers_per_bundle'] = 0
# WriteToFiles assigns shards per element, and each element here is a
# whole DataFrame batch, so split the batches to fill every shard.
if num_shards > 1:
pcoll = pcoll | 'SplitForShards' >> beam.FlatMap(
_split_for_shards, num_shards)
elif max_writers_per_bundle is not None:
write_to_files_kwargs['max_writers_per_bundle'] = max_writers_per_bundle

Expand Down
16 changes: 16 additions & 0 deletions sdks/python/apache_beam/dataframe/io_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,22 @@ def test_sharding_parameters(self):
file_naming=fileio.single_file_naming('out.csv'))
self.assertEqual(glob.glob(output + '*'), [output + 'out.csv'])

def test_num_shards_with_one_batch(self):
data = pd.DataFrame({
'label': [str(i) for i in range(10)], 'rank': range(10)
})
output = self.temp_dir()
with beam.Pipeline() as p:
df = convert.to_dataframe(p | beam.Create([data]), proxy=data[:0])
df.to_csv(output + 'out', num_shards=3, index=False)
files = sorted(glob.glob(output + 'out*'))
self.assertEqual([os.path.basename(f) for f in files],
['out-0000%d-of-00003' % i for i in range(3)])
shards = [pd.read_csv(f, dtype={'label': str}) for f in files]
self.assertTrue(all(len(shard) for shard in shards))
pd.testing.assert_frame_equal(
pd.concat(shards).sort_values('rank').reset_index(drop=True), data)

@pytest.mark.uses_pyarrow
@unittest.skipIf(
PD_VERSION >= (1, 4) and PYARROW_VERSION < (1, 0),
Expand Down
Loading