Multiplying a dataframe by a column… but values are strings?
I have a Dataframe that includes binary variables about respondents' behavior and the weight associated with each respondent. I'd like to multiply the scores by each respondents' weight so I can easily get a weighted average for the total behavior. The easiest thing would be to multiply the weight column against another column in a loop, as in df.columns*df.columns[i]. However, when I try to do, it throws an error of: 'can't multiply sequence by non-int of type 'str'.' I shouldn't have any strings, but in the off-chance there are, I tried to convert the df to numeric, like so df.apply(pd.to_numeric, errors='coerce'). But the problem still remains. I'm at my wits' end. Is there a workaround? Should I go row by row (and if so, do I need to loop through every column, or is there a nice clean way?).
You could always break apart your dataframe. for col in df.columns: for index, k in enumerate(df[col]): try: float(k) except: # Print out the row number, col and row value that's failing print(index, col, k) It's entirely possible you've got strings/none-types that are causing your multiplication. There's also df[col].apply(float) but it won't catch those errant rows.
loop appends last row n times to dict, instead of each row 1 time python
Division by 3 in Python
plot histogram in python using csv file as input
Running python script without installed libraries
In a django data model, is there any way to create a data field for each json attribute stored in a postgres table?
Updating an Existing XML Document in Python
Change in PANDAS .to_csv default formats? Or is it Anaconda?
URL does not work with formatted string but plain string does
Static class variables in Python — Lists & Objects [duplicate]
Python, Heroku & Memcachier - access settings.py variable
os.listdir outputting different files than there are in the folder
Python iterator not working as anticipated
Form placeholder in django doesn't show properly
How the OS handles python and subprocesses of a python script…?
Need help to work with characters longer than 2 or more bytes in Python
Python script to check Namenode status