Extract string from rules frozensets
Asked Answered
M

2

8

With the following statement:

rules = association_rules(frequent_itemsets, metric="lift", min_threshold=1.2) 

I get a data frame of rules in the format:

frozenset({'Co_Apples'})

But I need to extract a Co_Apples as a string.

How can I do that?

Minutia answered 12/9, 2018 at 9:21 Comment(3)
Thanks @ArnoldSchrijverMinutia
You seem to have a set of one element. You can convert it to a list, and take the first element: list(rules)[0].Favouritism
thanks @9000, the one item list is just an example but converting it to a list may be a good idea. I'll tryMinutia
M
7

You can use the following code to get a string from frozenset type columns and then cast the string to unicode.

rules["antecedents"] = rules["antecedents"].apply(lambda x: list(x)[0]).astype("unicode")
rules["consequents"] = rules["consequents"].apply(lambda x: list(x)[0]).astype("unicode")
Mucronate answered 19/3, 2019 at 21:8 Comment(1)
In case you have item combinations (a frozenset with more than one value), using list(x)[0] will only show the first value. You can use ', '.join( list(x) ) instead to separate the items with a comma. rules["antecedents"] = rules["antecedents"].apply(lambda x: ', '.join(list(x))).astype("unicode")Monandry
L
10
rules["antecedents"] = rules["antecedents"].apply(lambda x: ', '.join(list(x))).astype("unicode")

It is work for me. Thanks Frank Herfert save my day!

Lavonlavona answered 8/11, 2019 at 3:7 Comment(0)
M
7

You can use the following code to get a string from frozenset type columns and then cast the string to unicode.

rules["antecedents"] = rules["antecedents"].apply(lambda x: list(x)[0]).astype("unicode")
rules["consequents"] = rules["consequents"].apply(lambda x: list(x)[0]).astype("unicode")
Mucronate answered 19/3, 2019 at 21:8 Comment(1)
In case you have item combinations (a frozenset with more than one value), using list(x)[0] will only show the first value. You can use ', '.join( list(x) ) instead to separate the items with a comma. rules["antecedents"] = rules["antecedents"].apply(lambda x: ', '.join(list(x))).astype("unicode")Monandry

© 2022 - 2024 — McMap. All rights reserved.