我想把这张桌子换成
0 thg John 3.0
1 thg James 4.0
2 mol NaN 5.0
3 mol NaN NaN
4 lob NaN NaN在下面的表格中
df1
movie name rating
0 thg John 3.0
1 thg James 4.0
df2
movie rating
2 mol 5.0
df3
movie
3 mol
4 lob 如果每个数据都没有Nan值,也可以告诉方法是否需要相对于空白值而不是Nan进行分离。
发布于 2020-04-07 06:28:21
我认为,新目标DataFrame的启动不仅应该发生在 number of NaN值发生变化时(与上一行相比),而且还应该发生在该数字相同时,但NaN值位于不同列中。
因此,我提出以下方案:
dfs = [g.dropna(how='all',axis=1) for _,g in
df.groupby(df.isna().ne(df.isna().shift()).any(axis=1).cumsum())]您可以打印部分DataFrames (任意数量),运行:
n = 0
for grp in dfs:
print(f'\ndf No {n}:\n{grp}')
n += 1当您向源DataFrame添加包含以下内容的另一行时,我的解决方案相对于其他解决方案的优势变得显而易见:
5 NaN NaN 3.0它还包含1非空值(就像前面的两行)。另一种解决方案将将所有这些行视为包含以下内容的一个部分DataFrame:
movie rating
3 mol NaN
4 lob NaN
5 NaN 3.0正如您所看到的,具有 NaN值,而我的解决方案将这些行划分为2个单独的DataFrames,没有任何NaN。
发布于 2020-04-07 05:32:43
创建一个dfs列表,其中包含一个groupby和dropna:
dfs = [g.dropna(how='all',axis=1) for _,g in df.groupby(df.isna().sum(1))]
print(dfs[0],'\n\n',dfs[1],'\n\n',dfs[2])或迪克特:
d = {f"df{e+1}": g[1].dropna(how='all',axis=1)
for e,g in enumerate(df.groupby(df.isna().sum(1)))}
print(d['df1'],'\n\n',d['df2'],'\n\n',d['df3']) #read the keys of d movie name rating
0 thg John 3.0
1 thg James 4.0
movie rating
2 mol 5.0
movie
3 mol
4 lobhttps://stackoverflow.com/questions/61073320
复制相似问题