我有两个结构如下的数据框:

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中的列具有相同的格式? (即,用括号代替括号)

最佳答案

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

关于python - 将两个不同数据框的列强制为相同的数据类型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45516833/

10-12 21:52
查看更多