Skip to content
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

Fix patching a table with a DataFrame with a custom index #5645

Merged
merged 2 commits into from
Oct 16, 2023
Merged
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
58 changes: 43 additions & 15 deletions examples/reference/widgets/DataFrame.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"import pandas as pd\n",
Expand Down Expand Up @@ -81,7 +83,9 @@
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"df = pd.DataFrame({'int': [1, 2, 3], 'float': [3.14, 6.28, 9.42], 'str': ['A', 'B', 'C'], 'bool': [True, False, True]}, index=[1, 2, 3])\n",
Expand All @@ -101,7 +105,9 @@
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"from bokeh.models.widgets.tables import SelectEditor, NumberFormatter\n",
Expand All @@ -123,7 +129,9 @@
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"table.selection = [0, 2]\n",
Expand All @@ -147,7 +155,9 @@
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"custom_df = pd._testing.makeMixedDataFrame()\n",
Expand All @@ -167,7 +177,9 @@
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"pn.widgets.DataFrame(custom_df, autosize_mode='fit_columns', width=300)"
Expand All @@ -185,7 +197,9 @@
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"pn.widgets.DataFrame(custom_df, autosize_mode='fit_viewport')"
Expand All @@ -207,7 +221,9 @@
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"date_df = pd._testing.makeTimeDataFrame()\n",
Expand All @@ -227,7 +243,9 @@
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"agg_df = pd.concat([date_df, date_df.median().to_frame('Median').T, date_df.mean().to_frame('Mean').T])\n",
Expand All @@ -250,7 +268,9 @@
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"from bokeh.sampledata.population import data as population_data \n",
Expand All @@ -272,7 +292,9 @@
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"import numpy as np\n",
Expand All @@ -293,7 +315,9 @@
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"def stream_data():\n",
Expand All @@ -315,7 +339,9 @@
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"patch_table = pn.widgets.DataFrame(df[['int', 'float', 'str', 'bool']])\n",
Expand All @@ -342,7 +368,9 @@
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"patch_table.patch({\n",
Expand All @@ -353,7 +381,7 @@
" 'int': [\n",
" (slice(0, 2), [3, 2])\n",
" ]\n",
"})"
"}, as_index=False)"
]
},
{
Expand Down
80 changes: 80 additions & 0 deletions panel/tests/widgets/test_tables.py
Original file line number Diff line number Diff line change
Expand Up @@ -959,6 +959,86 @@ def test_tabulator_patch_with_dataframe(document, comm):
if col != 'index':
np.testing.assert_array_equal(table.value[col].values, expected[col])

def test_tabulator_patch_with_dataframe_custom_index(document, comm):
df = pd.DataFrame(dict(A=[1, 4, 2]), index=['foo1', 'foo2', 'foo3'])
df_patch = pd.DataFrame(dict(A=[10]), index=['foo2'])

table = Tabulator(df)

model = table.get_root(document, comm)

table.patch(df_patch)

expected = {
'index': np.array(['foo1', 'foo2', 'foo3']),
'A': np.array([1, 10, 2]),
}
for col, values in model.source.data.items():
expected_array = expected[col]
np.testing.assert_array_equal(values, expected_array)
if col != 'index':
np.testing.assert_array_equal(table.value[col].values, expected[col])

def test_tabulator_patch_with_dataframe_custom_index_name(document, comm):
df = pd.DataFrame(dict(A=[1, 4, 2]), index=['foo1', 'foo2', 'foo3'])
df.index.name = 'foo'
df_patch = pd.DataFrame(dict(A=[10]), index=['foo2'])
df.index.name = 'foo'

table = Tabulator(df)

model = table.get_root(document, comm)

table.patch(df_patch)

expected = {
'foo': np.array(['foo1', 'foo2', 'foo3']),
'A': np.array([1, 10, 2]),
}
for col, values in model.source.data.items():
expected_array = expected[col]
np.testing.assert_array_equal(values, expected_array)
if col != 'foo':
np.testing.assert_array_equal(table.value[col].values, expected[col])

def test_tabulator_patch_with_complete_dataframe_custom_index(document, comm):
df = makeMixedDataFrame()[['A', 'B', 'C']]
df.index = [0, 1, 2, 3, 10]

table = Tabulator(df)

model = table.get_root(document, comm)

table.patch(df)

expected = {
'index': np.array([0, 1, 2, 3, 10]),
'A': np.array([0, 1, 2, 3, 4]),
'B': np.array([0, 1, 0, 1, 0]),
'C': np.array(['foo1', 'foo2', 'foo3', 'foo4', 'foo5']),
}
for col, values in model.source.data.items():
expected_array = expected[col]
np.testing.assert_array_equal(values, expected_array)
if col != 'index':
np.testing.assert_array_equal(table.value[col].values, expected[col])

def test_tabulator_patch_with_dataframe_custom_index_multiple_error(document, comm):
df = pd.DataFrame(dict(A=[1, 4, 2]), index=['foo1', 'foo1', 'foo3'])
# Copy to assert at the end that the original dataframe hasn't been touched
original = df.copy()
df_patch = pd.DataFrame(dict(A=[20, 10]), index=['foo1', 'foo1'])

table = Tabulator(df)

with pytest.raises(
ValueError,
match=r"Patching a table with duplicate index values is not supported\. Found this duplicate index: 'foo1'"
):
table.patch(df_patch)

pd.testing.assert_frame_equal(table.value, original)

def test_tabulator_patch_with_dataframe_not_as_index(document, comm):
df = makeMixedDataFrame().sort_values('A', ascending=False)
table = Tabulator(df)
Expand Down
24 changes: 18 additions & 6 deletions panel/widgets/tables.py
Original file line number Diff line number Diff line change
Expand Up @@ -804,15 +804,27 @@ def patch(self, patch_value, as_index=True):
self.patch(patch_value_dict, as_index=as_index)
elif isinstance(patch_value, dict):
columns = list(self.value.columns)
patches = {}
for k, v in patch_value.items():
for (ind, value) in v:
if isinstance(ind, slice):
ind = range(ind.start, ind.stop, ind.step or 1)
values = []
for (patch_ind, value) in v:
data_ind = patch_ind
if isinstance(patch_ind, slice):
data_ind = range(patch_ind.start, patch_ind.stop, patch_ind.step or 1)
if as_index:
self.value.loc[ind, k] = value
if not isinstance(data_ind, range):
patch_ind = self.value.index.get_loc(patch_ind)
if not isinstance(patch_ind, int):
raise ValueError(
'Patching a table with duplicate index values is not supported. '
f'Found this duplicate index: {data_ind!r}'
)
self.value.loc[data_ind, k] = value
else:
self.value.iloc[ind, columns.index(k)] = value
self._patch(patch_value)
self.value.iloc[data_ind, columns.index(k)] = value
values.append((patch_ind, value))
patches[k] = values
self._patch(patches)
else:
raise ValueError(
f"Patching with a patch_value of type {type(patch_value).__name__} "
Expand Down
Loading