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

为何出现'string indices must be integer'错误?如何统计唯一玩家数?

Fixing the TypeError: 'string indices must be integer'

Ah, I spot the exact issue here—you're trying to index a file path string instead of your loaded Pandas DataFrame when calculating unique players. Let's break this down clearly:

What caused the error

You assigned the filename string to df:

df = "purchase_data.json"

Then you tried to access df['SN'], but df is just a plain text string, not the DataFrame with your game data. Strings only accept integer indices (like df[0] to get the first character), which is why you're seeing that "string indices must be integer" error.

Corrected Code

Here's the fixed version where we use the actual DataFrame variable (data_file_pd) instead of the filename string:

# Dependencies
import pandas as pd

# Save path to data set in a variable (renamed to avoid confusion)
file_path = "purchase_data.json"

# Use Pandas to read data
data_file_pd = pd.read_json(file_path)
data_file_pd.head()

# Find total number of unique players
player_count = len(data_file_pd['SN'].unique())
print(player_count)  # Optional: print to confirm the result

Key Fixes

  • Renamed the filename variable to file_path to avoid mixing it up with DataFrame objects (a simple but effective practice to prevent bugs)
  • Swapped df['SN'].unique() for data_file_pd['SN'].unique()—since data_file_pd is the loaded DataFrame that contains your player screen name data

This will resolve the TypeError and correctly calculate the number of unique players using their screen names.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:14:18