2017-08-04 90 views
1

我有两个dataframes被构造为这样:强制列相同的数据类型

print(product_combos1.head(n=5)) 
      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 

print(testing_df.head(n=5)) 
        product_id Length 
transaction_id       
001      [P01]  1 
002     [P01, P02]  2 
003    [P01, P02, P09]  3 
004     [P01, P03]  2 
005    [P01, P03, P05]  3 

我怎么能强迫的testing_df,使其在同一的“PRODUCT_ID”列格式为product_combos1 df中的列? (即 - 括号而不是括号)

回答

1

python元组显示在圆括号中。列表显示在括号中。

更改数据框

testing_df['product_id'] = testing_df['product_id'].apply(tuple) 
testing_df 

        product_id Length 
transaction_id       
1      (P01,)  1 
2     (P01, P02)  2 
3    (P01, P02, P09)  3 
4     (P01, P03)  2 
5    (P01, P03, P05)  3 

制作副本

testing_df.assign(product_id=testing_df.product_id.apply(tuple)) 

        product_id Length 
transaction_id       
1      (P01,)  1 
2     (P01, P02)  2 
3    (P01, P02, P09)  3 
4     (P01, P03)  2 
5    (P01, P03, P05)  3 

当然,除非那些实际上是字符串。然后用括号替换括号。

testing_df.assign(product_id=testing_df.product_id.str.replace('\[(.*)\]', r'(\1)')) 

        product_id Length 
transaction_id       
1       (P01)  1 
2     (P01, P02)  2 
3    (P01, P02, P09)  3 
4     (P01, P03)  2 
5    (P01, P03, P05)  3 
+0

唯一的问题是,我的DF的第一线已经从去'[“P01”]'来'(“P01”,)'我不知道为什么“”已添加到第一行 – zsad512

+0

啊,所以列元素是列表,你应用'元组'。是的,另一个数据框没有长度一个元组。这个长度有一个列表。 Python用'(x,)'显示长度的一个元组,用逗号区分表达式'(x)'。这只会评估为'x' – piRSquared

+0

当我试图比较两个数据帧时,这会导致任何复杂吗?如果你能提供帮助,请参阅[link](https://stackoverflow.com/questions/45515412/pandas-return-partial-matches-between-rows-of-two-dataframes)。 – zsad512

相关问题