У нас есть файл Excel в хранилище файлов, который содержит более 10 000 столбцов данных JSON в каждом файле Excel.
например, образец, как показано ниже.
json:
{"SearchName":"","Id":"","RequestType":"","StartDateUtc":"2022-12-01T00:00:00Z","EndDateUtc":"2023-04-28T00:00:00Z","RecordType":null,"Workload":"","Operations":[],"Users":["d503246e-285c-41bc-8b0a-bc79824146ea,[email protected],ab6019a4-851c-4af2-8ddc-1e03ee9be97a,[email protected],85ff7cda-5f2d-4d32-b51c-b88ad4d55b5a,[email protected],48168530-659c-44d3-8985-65f9b0af2b85,[email protected],0937a1e5-8a68-4573-ae9c-e13f9a2f3617,[email protected],c822dd8b-0b79-4c13-af1e-bc080b8108c5,[email protected],ca0de5ba-6ab2-4d34-b19d-ca702dcbdb8d,[email protected]"],"ObjectIds":[],"IPAddresses":[],"SiteIds":null,"AssociatedAdminUnits":[],"FreeText":"multifactor","ResultSize":0,"TimeoutInSeconds":345600,"ScopedAdminWithoutAdminUnits":false}
Мы просто хотим изменить значение хеша пользователя на обычные значения маски.
вот так: [email protected] в [email protected] для пользователей файлов Excel.
Каждый раз, когда мы вручную копируем данные пользователей и маскировку, как показано ниже, это отнимает у нас много времени. Затем, после того, как мы получили результат, мы просто заменили значение хеш-функции выходными данными.
import random
main=['[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]']
l=["0e07209b-807b-4938-8bfd-f87cee98e924,[email protected],c747a82c-656e-40eb-9194-88c4a0f8061e"]
n=len(l)
print(n)
print(random.sample(main,n))
Мой вопрос. Есть ли какой-либо способ в блоках данных Azure заменить все хэш-значения ключа json пользователя файла Excel на случайных пользователей, подобных этому [email protected], за один раз и перезаписать обратно в определенное место?
привет, Фурас! Спасибо за ваш ответ. Когда я пытаюсь прочитать Excel и заполнить блоки данных, я получаю вот такую ошибку [Errno 2] No such file or directory: '/dbfs/FileStore/Book111.xlsx'. но у меня есть файл Excel в том же каталоге.
возможно, настоящий путь — это /some/folder/dbfs/FileStore/Book111.xlsx, или это должен быть относительный путь без первого /. Возможно, проверьте «текущий рабочий каталог» os.getcwd() и что у вас в этой папке os.listdir()






Как вы упомянули, вы хотите изменить значение хэша пользователя на обычные значения маски.
Я попробовал следующий подход:
sample_json = """
{"SearchName":"","Id":"","RequestType":"","StartDateUtc":"2022-12-01T00:00:00Z","EndDateUtc":"2023-04-28T00:00:00Z","RecordType":null,"Workload":"","Operations":[],"Users":["d503246e-285c-41bc-8b0a-bc79824146ea,[email protected],ab6019a4-851c-4af2-8ddc-1e03ee9be97a,[email protected],85ff7cda-5f2d-4d32-b51c-b88ad4d55b5a,[email protected],48168530-659c-44d3-8985-65f9b0af2b85,[email protected],0937a1e5-8a68-4573-ae9c-e13f9a2f3617,[email protected],c822dd8b-0b79-4c13-af1e-bc080b8108c5,[email protected],ca0de5ba-6ab2-4d34-b19d-ca702dcbdb8d,[email protected]"],"ObjectIds":[],"IPAddresses":[],"SiteIds":null,"AssociatedAdminUnits":[],"FreeText":"multifactor","ResultSize":0,"TimeoutInSeconds":345600,"ScopedAdminWithoutAdminUnits":false}
"""
masked_emails = [
'[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]',
'[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]',
'[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]',
'[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]'
]
def mask_emails(json_str):
try:
data = json.loads(json_str)
users = data.get("Users", [])
if users:
original_emails = users[0].split(',')
masked = random.sample(masked_emails, len(original_emails))
data["Users"] = [','.join(masked)]
return json.dumps(data)
except Exception as e:
return json_str
mask_emails_udf = udf(mask_emails, StringType())
data = [(sample_json,)]
df = spark.createDataFrame(data, ["json_column"])
df = df.withColumn("transformed", mask_emails_udf(col("json_column")))
display(df)
В приведенном выше коде я маскирую адреса электронной почты в данных JSON. Чтение данных JSON, замена адресов электронной почты пользователей замаскированными значениями и последующая запись преобразованного JSON обратно.
Полученные результаты:
transformed
{"SearchName": "", "Id": "", "RequestType": "", "StartDateUtc": "2022-12-01T00:00:00Z", "EndDateUtc": "2023-04-28T00:00:00Z", "RecordType": null, "Workload": "", "Operations": [], "Users": ["[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected]"], "ObjectIds": [], "IPAddresses": [], "SiteIds": null, "AssociatedAdminUnits": [], "FreeText": "multifactor", "ResultSize": 0, "TimeoutInSeconds": 345600, "ScopedAdminWithoutAdminUnits": false}
[Ошибка 2] Нет такого файла или каталога: «/dbfs/FileStore/Book111.xlsx»
В ошибке упоминается, что интерпретатор Python не может найти указанный файл Excel по заданному пути в вашей DBFS.
Чтобы устранить вышеуказанную ОШИБКУ и записать результаты в формате xlsx, я попробовал следующий подход:
pandas_df = df.toPandas()
dir_path = "/FileStore/tables/"
dbutils.fs.mkdirs(dir_path)
file_path = dir_path + "transformed_data.xlsx"
local_file_path = "/tmp/transformed_data.xlsx"
pandas_df.to_excel(local_file_path, index=False, engine='openpyxl')
dbutils.fs.cp("file:" + local_file_path, "dbfs:" + file_path)
print(f"File saved to {file_path}")
Полученные результаты:
dbutils.fs.ls("/FileStore/tables/transformed_data.xlsx")
[FileInfo(path='dbfs:/FileStore/tables/transformed_data.xlsx', name='transformed_data.xlsx', size=5623, modificationTime=1720070340000)]
привет, Дилип, спасибо за ваши ответы, как уже упоминалось выше, у меня есть файл Excel в хранилище файлов, он содержит более 10 000 столбцов данных JSON. Например, 10 000 json. для 1 json я уже знаю, как самому делать обычный код Python. этот json предоставляет образец структуры .wt, в котором вы сохранили sample_json
даже я пытаюсь, мне нужно прочитать весь Excel и выполнить преобразование пользователей
@dataGreek можешь попробовать это?
def Mask_emails(user_list): верните ["[email protected]" для _ в user_list] для столбца в df.columns: для idx, json_data в df[col].items(): попробуйте: json_obj = json.loads(json_data ) если «Пользователи» в json_obj: json_obj['Users'] = Mask_emails(json_obj['Users']) df.at[idx, col] = json.dumps(json_obj), кроме (json.JSONDecodeError, TypeError): продолжить
привет, Дилип, спасибо за комментарий, во-первых, можно ли прочитать файл Excel в Spark, если да, не могли бы вы предоставить краткий скриншот того, как вы это сделали, а также df. Первый шаг — прочитать файл Excel. Обычно, когда я пытаюсь прочитать файл Excel. я получаю ошибку.
%pip install openpyxl %pip install xlrd Установите эти 2 библиотеки
Импорт Pandas As PD DBFS_INPUT_PATH = 'dbfs: /filestore/tables/sample_excel_file.xlsx' local_inpat_path = '/tmp/sample_excel_file.xlsx' dbutils.fs.cp (dbfs_inpat_path _input_path ) df_readinput.display()
Дайте мне знать, если помогло вам.
10 000 столбцов — это небольшой набор данных — вы можете использовать даже цикл for для работы с каждой строкой отдельно, чтения JSON, преобразования в словарь, обновления данных, преобразования их обратно в JSON и добавления в строку.