首页 > 解决方案 > 为什么我会丢失循环中的所有输出值,除了最后一个?

问题描述

我正在使用列表理解来遍历两个唯一列表,我的代码似乎正在工作,但是当我检查我的最终数据框时,看起来我只有第一个列表中的一个值的输出。有谁知道为什么我会丢失除最终值之外的所有循环输出?我应该从地理列中看到五个独特的地理,但我只看到一个。谢谢!

# Starting time before Loop:
t1 = time.time()

# Create Unique Lists of Geography and Product:
geo_list = list(data5['Geography'].unique())
prod_list = list(data5['Product'].unique())

# Use List Comprehension to Loop Through Dataframe based on Geography and Product:
[(g,p) for g in geo_list for p in prod_list]
new_df = data5[(data5['Geography']==g) & (data5['Product']==p)]
new_df['pn'] = new_df['Price']-new_df['Price'].shift(-1)
new_df['price_d'] = np.divide((new_df['Price']+new_df['Price'].shift(1)),2)
new_df['dn'] = new_df['Unit_Sales']-new_df['Unit_Sales'].shift(-1)
new_df['dd'] = np.divide((new_df['Unit_Sales']+new_df['Unit_Sales'].shift(1)),2)
new_df['Delta_Demand'] = np.divide(new_df['dn'].values,new_df['dd'].values)*100
new_df['Delta_Price'] = np.divide(new_df['pn'].values,new_df['price_d'].values)*100
new_df['ped'] = np.divide(new_df['Delta_Demand'].values,new_df['Delta_Price'].values)

# Keep only columns we need:        
new_df = new_df[['Geography', 'Product', 'Price', 'Unit_Sales', 'ped']]
unmatch = data5[(data5.Geography.isin(new_df.Geography)) & (~data5.Product.isin(new_df.Product)) & (~data5.Price.isin(new_df.Price)) & (~data5.Unit_Sales.isin(new_df.Unit_Sales))]
        
# Concat together:
df_final = pd.concat([new_df, unmatch],ignore_index=True)
t2 = time.time()
# Time taken by Loop:
df_final['Geography'].unique()
array(["Kroger Corp w/ Roundy's-RMA - Groc"], dtype=object)
#print("Time taken by Loop: %.6f" %(t2 - t1))

标签: pythonpandasloops

解决方案


推荐阅读