假设我有一份包含用户及其薪资记录的 excel 表/csv。我在数据库中为每个用户创建了一个帐户,并希望使用数据库中的 ID 为每个用户创建薪资记录。
import polars as pl
# Create the DataFrame with repeated entries for John and Jane
df = pl.DataFrame({
"first_name": ["John", "Jane", "Alice", "Bob", "John", "Jane", "John", "Jane"],
"middle_name": ["A.", "B.", "C.", "D.", "A.", "B.", "A.", "B."],
"last_name": ["Doe", "Smith", "Johnson", "Brown", "Doe", "Smith", "Doe", "Smith"],
"salary": [50000, 60000, 55000, 62000, 50000, 60000, 50000, 60000],
"date": ["2023-01-15", "2023-02-20", "2023-03-05", "2023-04-10", "2023-05-15", "2023-06-20", "2023-07-15", "2023-08-20"]
})
print(df)
shape: (8, 5)
┌────────────┬────────────┬────────────┬────────┬────────────┐
│ first_name │ middle_name│ last_name │ salary │ date │
│ --- │ --- │ --- │ --- │ --- │
│ str │ str │ str │ i64 │ date │
├────────────┼────────────┼────────────┼────────┼────────────┤
│ John │ A. │ Doe │ 50000 │ 2023-01-15 │
│ Jane │ B. │ Smith │ 60000 │ 2023-02-20 │
│ Alice │ C. │ Johnson │ 55000 │ 2023-03-05 │
│ Bob │ D. │ Brown │ 62000 │ 2023-04-10 │
│ John │ A. │ Doe │ 50000 │ 2023-05-15 │
│ Jane │ B. │ Smith │ 60000 │ 2023-06-20 │
│ John │ A. │ Doe │ 50000 │ 2023-07-15 │
│ Jane │ B. │ Smith │ 60000 │ 2023-08-20 │
└────────────┴────────────┴────────────┴────────┴────────────┘
#Get unique values
subset_df = df.select(["first_name", "middle_name", "last_name"])
unique_subset_df = subset_df.unique()
for row in subset_df.select(pl.struct(pl.all()).value_counts()):
# create acoount
用户列表及其对应的id如下
users = [
{'id': 1, 'first_name': 'John', 'middle_name': 'A.', 'last_name': 'Doe'},
{'id': 2, 'first_name': 'Jane', 'middle_name': 'B.', 'last_name': 'Smith'},
{'id': 3, 'first_name': 'Alice', 'middle_name': 'C.', 'last_name': 'Johnson'},
{'id': 4, 'first_name': 'Bob', 'middle_name': 'D.', 'last_name': 'Brown'}
]
# Note:The data above can also be transformed into a list of tuples
我怎样才能用该字典列表中相应的 ID 替换数据框的、和列first_name
中middle_name
的值?last_name