我正在使用Python。我想根据两列的值拆分数据框。每次值对更改时,我都希望在此位置拆分数据框。
示例:
df = pd.DataFrame({'Distance':[1,1,1,1,3,3,3], 'labels':[1,2,2,2,4,4,5]})
df=
Distance labels
0 1 1
1 1 2
2 1 2
3 1 2
4 3 4
5 3 4
6 3 5
我想获得:
list_of_dfs[0]=
Distance labels
0 1 1
list_of_dfs[1]=
Distance labels
1 1 2
2 1 2
3 1 2
list_of_dfs[2]=
Distance labels
4 3 4
5 3 4
list_of_dfs[3]=
Distance labels
6 3 5
这是它的工作方式:
l = [1,4,6,7]
l_mod = [0] + l + [max(l)+1]
list_of_dfs = [df.iloc[l_mod[n]:l_mod[n+1]] for n in range(len(l_mod)-1)]
我的问题:
如何自动获取数组l = [1,4,6,7]? 这就是我完成任务所需的全部!
答案 0 :(得分:1)
使用pd.duplicates查找唯一行。
# use duplicated to determine rows that are original and create list
ind = df[~df.duplicated()].index.tolist()
# account for the last row, append value one greater than maximum index.
ind.append(df.shape[0])
# create dictionary for dataframe.
dfs = {}
# use iloc to create new dataframes, then add to dictionary.
for i in range(len(ind)-1):
df_temp = df.iloc[ind[i]:ind[i+1], :]
dfs[i] = df_temp
从字典中检索数据框:
df0 = dfs[0]
Distance labels
0 1 1
df1 = dfs[1]
print(df1)
Distance labels
1 1 2
2 1 2
3 1 2