TypeError: string indices must be integers when trying to use dictionary of dataframes

Question:

I have a large dataframe that has an id column and a price column (along with other columns but they are irrelevant here). For each id there are multiple positive and negative prices. Below is code to seperate my large dataframe into seperate dataframes for each id with all of the prices associated with that id. I am trying to then use a loop to go through each id dataframe and put the negative numbers into a list.

dfs_by_id = dict(tuple(odds_df.groupby('id')))
print(dfs_by_id)
for df in dfs_by_id:
    temp_list = np.array(df['price'])
    temp_neg_list = temp_list[temp_list < 0]
    print(temp_neg_list)

But I recieve this error:

TypeError: string indices must be integers
Asked By: JackW24

||

Answers:

Instead of converting your dataframe to numpy array, try this:

dfs_by_id = dict(tuple(odds_df.groupby('id')))
print(dfs_by_id)
for df in dfs_by_id.values():
    temp_neg_list = np.array(df[df['price'] < 0]['price'])
    print(temp_neg_list)
Answered By: Divyessh
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.