传递函数至另一个函数时触发TypeError的原因及解决方案
TypeError: 'function' object is not subscriptable & How to Fix It The Root Cause
When you call classify_playlist(analyze_playlist), you're passing the function object analyze_playlist directly to classify_playlist—not the DataFrame that analyze_playlist returns when you run it.
Inside classify_playlist, you try to use func[['danceability', ...]] to access columns, but func here points to a function, not a pandas DataFrame. Functions don't support subscript (square bracket) access, which is exactly why this error pops up.
How to Fix It
You have two straightforward solutions, depending on how you want to structure your code:
Solution 1: Pass the Result of analyze_playlist (Simplest)
First, run analyze_playlist with the necessary arguments (like your Spotify playlist ID or URL) to get the DataFrame it returns, then pass that DataFrame to classify_playlist.
Example:
# Replace 'your_playlist_id' with your actual playlist ID/URL playlist_data = analyze_playlist('your_playlist_id') # Now pass the DataFrame to classify_playlist classification_result = classify_playlist(playlist_data)
Pro tip: Rename the func parameter in classify_playlist to something like playlist_df—this makes your code way more readable and avoids confusion between functions and data.
Solution 2: Modify classify_playlist to Handle the Function + Its Arguments
If you want classify_playlist to handle calling analyze_playlist for you, update its definition to accept the function and any arguments it needs:
def classify_playlist(func, *func_args): # First run the function to get the DataFrame playlist_df = func(*func_args) spotify = pd.read_csv('../OUTPUT/spotify.csv') spotify.drop(columns=['Unnamed: 0'], inplace=True) y = spotify['intervals'].values X = spotify[['danceability', 'energy', 'loudness', 'speechiness', 'acousticness', 'instrumentalness', 'liveness', 'valence']].values X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) forest = RandomForestClassifier(n_estimators=200) forest.fit(X_train, y_train) # Now use the actual DataFrame for column access tx = playlist_df[['danceability', 'energy', 'loudness', 'speechiness', 'acousticness', 'instrumentalness', 'liveness', 'valence']].values testdata = forest.predict(tx) return testdata
Then call it like this (pass the function followed by its required arguments):
classification_result = classify_playlist(analyze_playlist, 'your_playlist_id')
Quick Recap
- You tried to treat a function like a DataFrame (using
[]), which isn't allowed in Python. - Either pass the result of
analyze_playlisttoclassify_playlist, or modifyclassify_playlistto call the function internally with its arguments.
内容的提问来源于stack exchange,提问作者Lor_lab

