PY
py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
def install(package):
__import__('os').system(f"pip3 install -qq --target='/usercode' {package}")
install('tabulate')
import pandas as pd
from tabulate import tabulate
print("The original question was posed on stack as 'https://stackoverflow.com/q/79421320/4371981' Python-Polars: Expression to get length of lists in a structIn Python Polars, I am trying to extract the length of the lists inside a struct to re-use it in an expression.\n\nThe question and the original code attempted to use python polars and was not complete... and unfortunitely sololearn does not appear to support polars so I had to rewrite the code based on pandas and tabulate for creating pretty tables. Additionally asked AI to reference this code's use for this project and where else this code might be useful in other developments.\n\n")
print("The code compares a number (x) with ranges defined by pairs of lists ('low' and 'up') within dictionaries in another column (y). For each row, it checks if the number falls within the range defined by the 'low' and 'up' lists for at least one index. If it does for any index, the 'check' column for that row is set to True. Otherwise, it's set to False. The code is also robust to handle cases where the lists might have different lengths, be empty, or if the dictionary keys are missing. It also handles the case where the DataFrame itself is empty.\n")
def check_condition_pandas(df):
if df.empty:
return pd.DataFrame({'x': [], 'y': [], 'check': []}) # Handle empty DataFrame case directly
max_len = 0 # Initialize to 0
if not df.empty: # Avoid error on empty df
max_len = df['y'].apply(lambda y_val: max(len(y_val.get('low', [])), len(y_val.get('up', []))) if isinstance(y_val, dict) else 0).max()
def check_row(row):
row_results = []
y_val = row['y']
if not isinstance(y_val, dict): # Handle non-dictionary values in 'y'
return False
for i in range(max_len):
low_check = row['x'] >= y_val.get('low', [False]*max_len)[i] if i < len(y_val.get('low', [])) and isinstance(y_val.get('low'), list) else False
up_check = row['x'] <= y_val.get('up', [False]*max_len)[i] if i < len(y_val.get('up', [])) and isinstance(y_val.get('up'), list) else False
row_results.append(all([low_check, up_check]))
Enter to Rename, Shift+Enter to Preview
OUTPUT
Run