We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 482232b commit e31a1f0Copy full SHA for e31a1f0
frame/davidkhala/data/frame/pandas/__init__.py
@@ -1,7 +1,9 @@
1
import pandas as pd
2
def upsert(df, *primary_keys: str, record: dict):
3
index_keys = df.index.names if isinstance(df.index, pd.MultiIndex) else [df.index.name]
4
- condition = True
+ condition = pd.Series(True, index=df.index)
5
+ if df.columns.empty and df.index.empty:
6
+ return pd.DataFrame([record])
7
8
for key in primary_keys:
9
if key in df.columns:
@@ -17,7 +19,5 @@ def upsert(df, *primary_keys: str, record: dict):
17
19
for col, value in record.items():
18
20
if col in df.columns:
21
df.loc[match_indices, col] = value
- else:
- df = pd.concat([df, pd.DataFrame([record])], ignore_index=True)
22
-
23
- return df
+ return df
+ return pd.concat([df, pd.DataFrame([record])])
frame/tests/pandas_test.py
@@ -31,6 +31,16 @@ def test_upsert(self):
31
upsert(df, prim_key, record = new_record)
32
33
self.assertEqual(95, df.at[2, 'score'])
34
+ def test_upsert_empty(self):
35
+ df = pandas.DataFrame()
36
+ prim_key = 'id'
37
+ new_record = {'name': 'Charlie', 'score': 95, prim_key: 2}
38
+ upsert(df, prim_key, record=new_record)
39
+
40
41
+ df = pandas.DataFrame(columns=[prim_key]).set_index(prim_key)
42
43
44
def test_upsert2(self):
45
df = pandas.DataFrame([
46
{'School': 'Oxford', 'Country': 'UK', 'Students': 1000},
@@ -40,6 +50,7 @@ def test_upsert2(self):
50
record = {'School': 'Oxford', 'Country': 'UK', 'Students': new_students}
51
df = upsert(df, 'School', 'Country', record=record)
52
self.assertEqual(new_students, df.loc[('Oxford', 'UK')].Students)
53
+ print(df)
54
def test_upsert3(self):
55
56
0 commit comments