Skip to content

Commit c5a9850

Browse files
committed
update upsert
1 parent 5a85cd4 commit c5a9850

File tree

2 files changed

+15
-7
lines changed

2 files changed

+15
-7
lines changed

frame/davidkhala/data/frame/pandas/__init__.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,21 +7,20 @@ def upsert(df: pd.DataFrame, *primary_keys: str, record: dict, verify_integrity=
77

88
if original_index: df = df.reset_index()
99

10-
condition = pd.Series(True, index=df.index)
10+
condition = pd.Series(False, index=df.index)
1111
for key in primary_keys:
1212
if key not in df.columns:
1313
raise KeyError(f"Primary key '{key}' not found in DataFrame columns")
14-
condition &= (df[key] == record[key])
14+
condition |= (df[key] == record[key])
1515

16-
match_indices = df[condition].index
17-
18-
if not match_indices.empty:
16+
match_row_i = df[condition].index
17+
if not match_row_i.empty:
1918
for col, value in record.items():
2019
if col in df.columns:
21-
df.loc[match_indices, col] = value
20+
df.loc[match_row_i, col] = value
2221
else:
2322
df[col] = None
24-
df.loc[match_indices, col] = value
23+
df.loc[match_row_i, col] = value
2524
else:
2625
new_row = pd.DataFrame([record])
2726
df = pd.concat([df, new_row], ignore_index=True)

frame/tests/pandas_test.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,15 @@ def test_single_index2(self):
5353
self.assertEqual(2, len(df.columns))
5454
self.assertEqual(1, len(df.index.names))
5555

56+
def test_single_index3(self):
57+
df = self.single_index_df
58+
prim_key = df.index.name
59+
new_record = {'name': 'Charlie', 'score': 95, prim_key: 3}
60+
df = upsert(df, record =new_record)
61+
62+
self.assertEqual(3,len(df)) # should insert
63+
64+
5665
def test_empty(self):
5766
df = pandas.DataFrame()
5867
prim_key = 'id'

0 commit comments

Comments
 (0)