python - 为什么我会丢失循环中的所有输出值,除了最后一个?
问题描述
我正在使用列表理解来遍历两个唯一列表,我的代码似乎正在工作,但是当我检查我的最终数据框时,看起来我只有第一个列表中的一个值的输出。有谁知道为什么我会丢失除最终值之外的所有循环输出?我应该从地理列中看到五个独特的地理,但我只看到一个。谢谢!
# 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))
解决方案
推荐阅读
- isabelle - 在 Isabelle 中,如何以其他格式(如 S-expression、Json 格式...)打印状态(即要证明的子目标)?
- ruby-on-rails - FrozenStringLiteralComment 的 Rubocop 自动更正不起作用
- node.js - 无法读取sails Js Mongo DB中未定义的属性'columnName'
- pandas - 为什么 df.interpotale() 在我的 python3 中不起作用?为什么它返回完全相同的数据帧而没有任何插值?
- r - 我该如何解决这个 R 问题依赖 'animation' 不适用于包 'gganimate'
- git - 如何重置color.ui?
- mysql - MySQL:想要使用存储过程按一列对表进行排序,然后使用该排序来设置另一列的值
- windows - 适用于 Windows 的 Docker 的 DOCKER_BUILDKIT?
- android - 当我将灯附加到节点时,我必须移动灯的位置吗?那是因为我根本看不到光
- swift - 如何在 iPhoneX 中将全高应用到初始屏幕 - 故事板