Python For循环更新数据框

时间:2018-10-06 17:44:11

标签: python pandas loops dataframe

我正在尝试使用Python重新创建一个VBA宏。有人可以告诉我我应该使用的FOR语句,以便获得以下结果吗?非常感谢。

文件1:

Product Colour  Price
Book    NaN 5
Table   NaN 10
Chair   NaN 7

文件2:

Colour 
Blue 
Red 
Green

循环后的预期结果(文件1):

Product Colour Price    
Book    Blue    5
Table   Blue    10
Chair   Blue    7
Book    Red 5
Table   Red 10
Chair   Red 7
Book    Green   5
Table   Green   10
Chair   Green   7

2 个答案:

答案 0 :(得分:1)

首先将df1的值重复df2,然后将list comprehesion的{​​{1}}和chain用作:

Colour

答案 1 :(得分:0)

您可以使用列表推导,类似于嵌套的for循环:

df = pd.DataFrame([[product, colour, price] for colour in df2['Colour'] \
                   for product, price in zip(df1['Product'], df1['Price'])],
                  columns=['Product', 'Colour', 'Price'])

print(df)

  Product Colour  Price
0    Book   Blue      5
1   Table   Blue     10
2   Chair   Blue      7
3    Book    Red      5
4   Table    Red     10
5   Chair    Red      7
6    Book  Green      5
7   Table  Green     10
8   Chair  Green      7