I have a dataframe as below:
date uids
0 2018-11-23 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
1 2018-11-24 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
When I use set
to convert it to set it fails:
df['uids'] = set(df['uids']) # IT FAILS!
How should I convert list
into set
in place?
We can convert the list into a set using the set() command, where we have to insert the list name between the parentheses that are needed to be converted. Hence, in the above case, we have to type the set(the_names) in order to convert the names, present in the list into a set.
The simplest way to convert list to set in Python is by using the set() function. The set() method is used to convert an iterable element such as a list, dictionary, or tuple into the set.
For Converting a List into Pandas Core Data Frame, we need to use DataFrame Method from pandas Package.
Pandas series can be converted to a list using tolist() or type casting method. There can be situations when you want to perform operations on a list instead of a pandas object. In such cases, you can store the DataFrame columns in a list and perform the required operations.
You should use apply method of DataFrame API:
df['uids'] = df.apply(lambda row: set(row['uids']), axis=1)
or
df = df['uids'].apply(set) # great thanks to EdChum
You can find more information about apply method here.
Examples of use
df = pd.DataFrame({'A': [[1,2,3,4,5,1,1,1], [2,3,4,2,2,2,3,3]]})
df = df['A'].apply(set)
Output:
>>> df
0 set([1, 2, 3, 4, 5])
1 set([2, 3, 4])
Name: A, dtype: object
Or:
>>> df = pd.DataFrame({'A': [[1,2,3,4,5,1,1,1], [2,3,4,2,2,2,3,3]]})
>>> df['A'] = df.apply(lambda row: set(row['A']), axis=1)
>>> df
A
0 set([1, 2, 3, 4, 5])
1 set([2, 3, 4])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With