Python报错:SyntaxError: can't assign to function call 解决求助
First, let's break down why you're seeing that SyntaxError: can't assign to function call error. This usually pops up when you try to assign a value to something that isn't a valid variable target—like if you attempted to dynamically create variables (e.g., table_{i} = pd.crosstab(...) using string formatting directly in the assignment, which Python doesn't allow). Instead of cluttering your code with individual table_1, table_2 variables, the cleanest and most maintainable approach is to store your crosstabs in a dictionary.
Step-by-Step Solution
- Define your target column and columns to process: First, list out exactly which columns you want to generate crosstabs for (since you don't need to process all columns).
- Use a dictionary to store crosstabs: Loop through your target columns, generate each crosstab, and add it to the dictionary with a descriptive key (like the column name or a numbered identifier).
Example Code
Let's use a complete sample dataset to demonstrate how this works:
import pandas as pd # Sample dataset (expanding on your incomplete example) data_new = pd.DataFrame({ 'target': ['A', 'B', 'A', 'B', 'A', 'A'], 'col_1': ['X', 'Y', 'X', 'X', 'Y', 'X'], 'col_2': ['P', 'P', 'Q', 'Q', 'P', 'Q'], 'col_3': ['M', 'N', 'N', 'M', 'M', 'N'], 'col_ignore': [1,2,3,4,5,6] # Column we don't want to process }) target = 'target' # List of columns you want to create crosstabs for columns_to_process = ['col_1', 'col_2', 'col_3'] # Initialize an empty dictionary to hold all crosstabs crosstabs = {} # Loop through each column and generate the crosstab for col in columns_to_process: # Use the column name as the key for easy, readable access crosstabs[col] = pd.crosstab(data_new[target], data_new[col]) # If you prefer numbered keys like 'table_1', 'table_2', use this instead: # crosstabs[f'table_{columns_to_process.index(col)+1}'] = pd.crosstab(data_new[target], data_new[col]) # Access individual crosstabs from the dictionary print("Crosstab for col_1:") print(crosstabs['col_1']) print("\nCrosstab for col_2:") print(crosstabs['col_2'])
Why This Works
- Dictionaries let you dynamically store and retrieve crosstabs without needing to predefine every variable upfront. This is perfect when you don't know how many columns you'll process in advance.
- You avoid the syntax error because you're assigning values to valid dictionary keys (not trying to create variables on the fly with invalid syntax).
Alternative: Using exec (Not Recommended)
While you can use exec to create individual variables, this approach is generally discouraged—it makes code harder to read, debug, and maintain. But for completeness, here's how you might do it (though the dictionary method is far better):
for i, col in enumerate(columns_to_process, 1): exec(f'table_{i} = pd.crosstab(data_new[target], data_new["{col}"])') # Now table_1, table_2, table_3 exist in your namespace print(table_1)
Stick with the dictionary approach—it's cleaner, safer, and more aligned with Python best practices.
内容的提问来源于stack exchange,提问作者Prince

