Build dataframe for sunburst, treemap, or icicle when the path argument is provided.
(args)
| 1929 | |
| 1930 | |
| 1931 | def process_dataframe_hierarchy(args): |
| 1932 | """ |
| 1933 | Build dataframe for sunburst, treemap, or icicle when the path argument is provided. |
| 1934 | """ |
| 1935 | df: nw.DataFrame = args["data_frame"] |
| 1936 | path = args["path"][::-1] |
| 1937 | _check_dataframe_all_leaves(df[path[::-1]]) |
| 1938 | discrete_color = not _is_continuous(df, args["color"]) if args["color"] else False |
| 1939 | |
| 1940 | df = df.lazy() |
| 1941 | |
| 1942 | new_path = [col_name + "_path_copy" for col_name in path] |
| 1943 | df = df.with_columns( |
| 1944 | nw.col(col_name).alias(new_col_name) |
| 1945 | for new_col_name, col_name in zip(new_path, path) |
| 1946 | ) |
| 1947 | path = new_path |
| 1948 | # ------------ Define aggregation functions -------------------------------- |
| 1949 | agg_f = {} |
| 1950 | if args["values"]: |
| 1951 | try: |
| 1952 | df = df.with_columns(nw.col(args["values"]).cast(nw.Float64())) |
| 1953 | |
| 1954 | except Exception: # pandas, Polars and pyarrow exception types are different |
| 1955 | raise ValueError( |
| 1956 | "Column `%s` of `df` could not be converted to a numerical data type." |
| 1957 | % args["values"] |
| 1958 | ) |
| 1959 | |
| 1960 | if args["color"] and args["color"] == args["values"]: |
| 1961 | new_value_col_name = args["values"] + "_sum" |
| 1962 | df = df.with_columns(nw.col(args["values"]).alias(new_value_col_name)) |
| 1963 | args["values"] = new_value_col_name |
| 1964 | count_colname = args["values"] |
| 1965 | else: |
| 1966 | # we need a count column for the first groupby and the weighted mean of color |
| 1967 | # trick to be sure the col name is unused: take the sum of existing names |
| 1968 | columns = df.collect_schema().names() |
| 1969 | count_colname = ( |
| 1970 | "count" if "count" not in columns else "".join([str(el) for el in columns]) |
| 1971 | ) |
| 1972 | # we can modify df because it's a copy of the px argument |
| 1973 | df = df.with_columns(nw.lit(1).alias(count_colname)) |
| 1974 | args["values"] = count_colname |
| 1975 | |
| 1976 | # Since count_colname is always in agg_f, it can be used later to normalize color |
| 1977 | # in the continuous case after some gymnastic |
| 1978 | agg_f[count_colname] = nw.sum(count_colname) |
| 1979 | |
| 1980 | discrete_aggs = [] |
| 1981 | continuous_aggs = [] |
| 1982 | |
| 1983 | n_unique_token = _generate_temporary_column_name( |
| 1984 | n_bytes=16, columns=df.collect_schema().names() |
| 1985 | ) |
| 1986 | |
| 1987 | # In theory, for discrete columns aggregation, we should have a way to do |
| 1988 | # `.agg(nw.col(x).unique())` in group_by and successively unpack/parse it as: |
no test coverage detected