[英]Pandas adding length column to dataframe after converting list to tuple
我有兩個數據test_df
, test_df
是一個列表,而product_combos
df是元組。 我也將test_df
更改為元組,如下所示:
[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)
我現在嘗試將length列添加到test_df1
(計算每行中的字符串數)時遇到問題。
我嘗試過先添加長度列,然后轉換為元組,但是當我嘗試此操作時,長度列就消失了。 我也做了:
testing_df1['length'] = testing_df['product_id'].str.len()
但這只會增加一堆廢話。 我也嘗試過:
testing_df1['length'] = testing_df['product_id'].apply(len)
這似乎也不起作用。 我在做什么錯,我該如何解決?
工作正常
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.