我有以下两个 Dataframe
df=
city value
hyderabad 3
chennai 3
mumbai 5
pune 5
df1 =
id Name
1 *
2 *
3 *
4 *
5 *
我想将 Dataframe (df)拆分为多个 Dataframe ,为每个 Dataframe 生成一个组合,并将具有相同值的行分解
df = city value
hyderabad 3
mumbai 5
df = city value
hyderabad 3
pune 5
df = city value
chennai 3
mumbai 5
df = city value
chennai 3
pune 5
我希望根据value列将上述生成的 Dataframe 适配到df1中,并为每个组合生成id。最终的结果是这样的
['*|*|hyderabad|*|mumbai','*|*|hyderabad|*|pune','*|*|chennai|*|mumbai','*|*|chennai|*|pune']
下面是我为生成ID而编写的代码
result = []
attributelist = []
finallist = []
for c in product(*[g.index.tolist() for _, g in df.groupby("value")]): // this wil generate the dataframes fo different combinaytions
dff = df.loc[c, :]
for index,row in dff.iterrows():
df1.loc[df1['id'] == str(row['value']),'Name'] = row['city'] //maps to df1 in the exact postion based on the value
x = '|'.join(df1["Name"])
y = x+','.join(result)
attributelist.append(y)
finallist.append(attributelist[-1])
print(finallist)
finallist = ['*|*|hyderabad|*|mumbai','*|*|hyderabad|*|pune','*|*|chennai|*|mumbai','*|*|chennai|*|pune']
这里我只有四个组合,因此它可以快速生成ID,当有1000个组合时,它必须循环1000次才能生成1000个ID,这需要很多时间。
是否有任何有效的方法可以做到这一点而不必在每个 Dataframe 上循环并生成id?
暂无答案!
目前还没有任何答案,快来回答吧!