简体   繁体   English

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

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

I have two dataframes, the test_df was a list whereas the product_combos df was tuples. 我有两个数据test_dftest_df是一个列表,而product_combos df是元组。 I changed the test_df to tuples as well like so: 我也将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)

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). 我现在尝试将length列添加到test_df1 (计算每行中的字符串数)时遇到问题。

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: 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: 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