main.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import random
  2. import string
  3. import pandas as pd
  4. from pandas.api.types import is_bool_dtype, is_numeric_dtype
  5. from nicegui import ui
  6. def generate_random_dataframe(*, range_columns=(5, 8), range_rows=(5, 10)):
  7. """Returns a pandas dataframe with a random number of rows and columns, each
  8. containing random data of various data types.
  9. """
  10. # Generate random number of columns
  11. num_columns = random.randint(*range_columns)
  12. # Generate random column names
  13. column_names = [''.join(random.choices(string.ascii_letters, k=random.randint(3, 10))) for i in range(num_columns)]
  14. # Generate random data types for each column
  15. column_types = [random.choice([int, float, str, bool]) for i in range(num_columns)]
  16. # Generate random data for each row
  17. rows = []
  18. num_rows = random.randint(*range_rows)
  19. for i in range(num_rows):
  20. row = []
  21. for j in range(num_columns):
  22. if column_types[j] == int:
  23. row.append(random.randint(-100, 100))
  24. elif column_types[j] == float:
  25. row.append(random.uniform(-100, 100))
  26. elif column_types[j] == str:
  27. row.append(''.join(random.choices(string.ascii_letters, k=random.randint(3, 10))))
  28. elif column_types[j] == bool:
  29. row.append(random.choice([True, False]))
  30. rows.append(row)
  31. # Add a column with integers and the same name as another column
  32. column_name = random.choice(column_names)
  33. column_names.append(column_name + ' ID')
  34. column_types.append(int)
  35. for row in rows:
  36. row.append(random.randint(1, 100))
  37. # Create the dataframe
  38. return pd.DataFrame(rows, columns=column_names)
  39. def update(*, df: pd.DataFrame, r: int, c: int, value):
  40. df.iat[r, c] = value
  41. ui.notify(f"Set ({r}, {c}) to {value}")
  42. @ui.refreshable
  43. def home():
  44. df = generate_random_dataframe()
  45. with ui.header():
  46. ui.button("Randomize", on_click=home.refresh)
  47. with ui.row():
  48. for c, col in enumerate(df.columns):
  49. with ui.column():
  50. ui.label(col.capitalize())
  51. for r, row in enumerate(df.loc[:, col]):
  52. with ui.row().classes("h-8 items-center"):
  53. if is_numeric_dtype(df[col].dtype):
  54. cls = ui.number
  55. elif is_bool_dtype(df[col].dtype):
  56. cls = ui.checkbox
  57. else:
  58. cls = ui.input
  59. cls(value=row, on_change=lambda event, r=r, c=c: update(df=df, r=r, c=c, value=event.value))
  60. home()
  61. ui.run(native=True)