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

时间:2017-08-05 14:20:25

标签: python pandas dataframe

我有两个数据框,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)

我现在尝试将长度列添加到test_df1(计算每行中的字符串数)时遇到问题。

我尝试先添加长度列然后转换为元组,但是当我尝试这个时,长度列就会消失。我也做了:

testing_df1['length'] = testing_df['product_id'].str.len() 

但这只会增加一些废话。我也尝试过:

testing_df1['length'] = testing_df['product_id'].apply(len) 

这似乎也不起作用。我做错了什么,我该如何解决?

1 个答案:

答案 0 :(得分:0)

它工作正常

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