I have two dataframes, the test_df
was a list whereas the product_combos
df was tuples. I changed the test_df
to tuples as well like so:
[in] print(testing_df.head(n=5))
[out]
product_id
transaction_id
001 [P01]
002 [P01, P02]
003 [P01, P02, P09]
004 [P01, P03]
005 [P01, P03, P05]
[in] print(product_combos1.head(n=5))
[out]
product_id count length
0 (P06, P09) 36340 2
1 (P01, P05, P06, P09) 10085 4
2 (P01, P06) 36337 2
3 (P01, P09) 49897 2
4 (P02, P09) 11573 2
# Convert the lists to tuples
testing_df1 = testing_df['product_id'].apply(tuple)
I run into problems when I now try and add the length column to the test_df1
(which calculates the number of strings in each row).
I have tried first adding the length column and then converting to tuple, but the length column just disappears when I try this. I also did:
testing_df1['length'] = testing_df['product_id'].str.len()
But this just adds a row of nonsense. I also tried:
testing_df1['length'] = testing_df['product_id'].apply(len)
This doesnt seem to work either. What am I doing wrong and how can I fix it?
it's working fine
df = pd.DataFrame([[1,['a','b']],[2,['a','b','c']],[3,['c','b']],[4,['b','d']],[5,['c','a']]])
df:
0 1
0 1 [a,b]
1 2 [a, b, c]
2 3 [c, b]
3 4 [b, d]
4 5 [c, a]
df[1] = df[1].apply(tuple)
df['length'] = df[1].apply(len)
df:
0 1 length
0 1 (a, b) 2
1 2 (a, b, c) 3
2 3 (c, b) 2
3 4 (b, d) 2
4 5 (c, a) 2
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.