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

Time:10-02

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

CodePudding user response:

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)
  • Related