繁体   English   中英

熊猫将列表转换为元组后将长度列添加到数据帧

[英]Pandas adding length column to dataframe after converting list to tuple

我有两个数据test_dftest_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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM