为何出现'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_pathto avoid mixing it up with DataFrame objects (a simple but effective practice to prevent bugs) - Swapped
df['SN'].unique()fordata_file_pd['SN'].unique()—sincedata_file_pdis 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

