You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使Pandas新计算的Price Tier Index列仅显示数字并转为int类型?

解决Pandas中Price Tier Index列显示为object类型的问题

问题原因

你循环里用df.loc[i, ['Avg EQ Price']]取到的是单元素Series对象,而非单个数值。把这些Series添加到列表后,最终生成的Price Tier Index列会是object类型,显示时还会附带索引信息,和你遇到的问题一致。

解决方案

推荐用Pandas原生的向量化运算(比循环高效得多),一步到位生成int类型的列:

import pandas as pd
import numpy as np
import csv
import io
from IPython.display import display
from google.colab import files
uploaded = files.upload()    

men_bw_avg_eq_price = 0.28

df = pd.read_csv(io.BytesIO(uploaded["Men BW - competitive price tier analysis - REPULLED.csv"]))
df= df.fillna(0)

# 核心修改:向量化计算+转int类型
df['Price Tier Index'] = (df['Avg EQ Price'] / men_bw_avg_eq_price * 100).astype(int)

df[['Brand', 'Gender', 'Subcategory']] = df.Products.str.split("|", expand=True)
df_new = df[['Brand', 'Price Tier Index']]
display(df_new)

如果一定要保留循环逻辑,只需修改取数方式(去掉方括号取标量),并提前转int:

price_index = []
total_rows = len(df['Products']) 
for i in range(total_rows): 
      # 去掉方括号,获取单个数值而非Series
      pi_value = (df.loc[i, 'Avg EQ Price'] / men_bw_avg_eq_price) * 100  
      price_index.append(int(pi_value))  # 转成int后再添加到列表

df['Price Tier Index'] = price_index

验证结果

修改后可以用print(df['Price Tier Index'].dtype)查看列类型,会输出int64,显示效果就是纯数字,和你目标效果一致。

内容的提问来源于stack exchange,提问作者Baek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 12:10:39