Reputation: 453
Hi I have a dictionary below,
I want to split the dictionary value into two based on a comma present in the dictionary value, and then store the result in a new dataframe as follows:
For a particular dictionary entry, lets say the first one in our case:
(1, 5) - this is the key, and should be column 1 in a new dataframe (2,) - this is extracted from the value (pre-comma), and should be column 2 in the dataframe 1.0 - this is extracted from the value (post-comma), and should be column 3 in the dataframe
The same process should be repeated for all (4 in this case) key value pairs in the dictionary.
If rules is the name of the dictionary, I know I can access rules.keys(), and rules.values(), but what I do not understand is how do I access the comma split values in the dictionary because when I try something like rules.values() [1], it throws an error.
{(1, 5): ((2,), 1.0),
(2, 5): ((1,), 1.0),
(4,): ((2,), 1.0),
(5,): ((1, 2), 1.0)}
Output DF:
Col 1 Col2 Col3
(1, 5) (2,) 1.0
(2, 5) (1,) 1.0
(4,) (2,) 1.0
(5,) (1, 2) 1.0
Upvotes: 0
Views: 177
Reputation: 82785
Using a list comprehension.
Ex:
import pandas as pd
data = {(1, 5): ((2,), 1.0), (2, 5): ((1,), 1.0), (5,): ((1, 2), 1.0), (4,): ((2,), 1.0)}
df = pd.DataFrame([[k] + list(v) for k, v in data.items()], columns=["Col_1", "Col_2", "Col_3"])
print(df)
Output:
Col_1 Col_2 Col_3
0 (1, 5) (2,) 1.0
1 (2, 5) (1,) 1.0
2 (5,) (1, 2) 1.0
3 (4,) (2,) 1.0
Upvotes: 1