简体   繁体   中英

Rename dataframe in Python for loop

I am trying to rename a dataframe in each iteration of my for loop. For column "item" in the "data" dataframe, I would like to generate dataframes up to the number of unique items in "item" column.

for item in data.item.unique():
    data+"item" = data[data["item"] == item]

Use a dictionary:

frames = {}
for item in data['item'].unique():
    frames[item] = data[data['item'] == item]

IIUC,你可以只使用groupby

frames = {k:d for k,d in data.groupby('item')}

My advice is use dictionaries.

Your answer is this:

for i in data.item.unique():
    globals()[f'data{i}'] = data[data["item"] == i]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM