元组迭代向量化

时间:2019-03-27 17:54:29

标签: python pandas vectorization

我有一个熊猫代码,正在迭代元组,我正在尝试将其向量化。

我要迭代的元组列表:

[('Morden', 35672, 'Morden Hall Park, Surrey'),
 ('Morden', 73995, 'Morden Hall Park, Surrey'),
 ('Newbridge', 120968, 'Newbridge, Midlothian'),
 ('Stroud', 127611, 'Stroud, Gloucestershire')]

有效的元组迭代代码为:

for tuple_ in result_tuples:
    listing_looking_ins1.loc[:,'looking_in']\ 
    [(listing_looking_ins1.listing_id ==tuple_[1]) &
     (listing_looking_ins1.looking_in ==tuple_[0])] = tuple_[2]

我尝试编写一个可与​​apply方法一起使用的func,但是它不起作用:

result_tuples_df = pd.DataFrame(result_tuples)

def replace_ (row):
    row.loc[:,'looking_in'][(listing_looking_ins1.listing_id\ 
    \==result_tuples_df[1]) &
    (listing_looking_ins1.looking_in\==result_tuples_df[0])] \
     = result_tuples_df[2]

listing_looking_ins1.apply(replace_, axis=1)

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以将元组列表转换为DataFrame并将其与原始列表合并:

result_tuples_df = pd.DataFrame(result_tuples,
                                columns=['listing_id', 'looking_in', 'result'])

df = listing_looking_ins1.merge(result_tuples_df)

print(df)

输出:

  listing_id  looking_in                    result
0     Morden       35672  Morden Hall Park, Surrey
1     Morden       73995  Morden Hall Park, Surrey
2  Newbridge      120968     Newbridge, Midlothian
3     Stroud      127611   Stroud, Gloucestershire

然后,如果要在looking_in列中显示结果:

df.drop('looking_in', 1).rename(columns={'result': 'looking_in'})

输出:

  listing_id                looking_in
0     Morden  Morden Hall Park, Surrey
1     Morden  Morden Hall Park, Surrey
2  Newbridge     Newbridge, Midlothian
3     Stroud   Stroud, Gloucestershire

P.S。在您的代码中,您可以通过以下方式设置值:

listing_looking_ins1.loc[:,'looking_in'][...] = ...

这是在DataFrame副本上设置值。请参阅How to deal with SettingWithCopyWarning in Pandas?,了解为什么以及如何避免这样做

P.P.S。由于您询问了向量化和使用apply的问题,因此您可能还希望查看有关不同操作性能的答案https://stackoverflow.com/a/24871316/6792743