python - 如何将不同列大小的熊猫数据框拆分为单独的数据框?
解决方案
如果您有一个说 10 列的数据框,并且您想将具有 3 个NaN
值的记录与具有 1 的结果数据框一样放在另一个结果数据框中NaN
,您可以按如下方式执行此操作:
# evaluate the number of NaNs per row
num_counts=df.isna().sum('columns')
# group by this number and add the grouped
# dataframe to a dictionary
results= dict()
num_counts=df.isna().sum('columns')
for key, sub_df in df.groupby(num_counts):
results[key]= sub_df
执行此代码后,结果包含子集,df
其中每个子集包含相同数量的NaN
s(因此相同数量的非NaN
s)。
如果要将结果写入 excel 文件,只需执行以下代码:
with pd.ExcelWriter('sorted_output.xlsx') as writer:
for key, sub_df in results.items():
# if you want to avoid the detour of using dicitonaries
# just replace the previous line by
# for key, sub_df in df.groupby(num_counts):
sub_df.to_excel(
writer,
sheet_name=f'missing {key}',
na_rep='',
inf_rep='inf',
float_format=None,
index=True,
index_label=True,
header=True)
例子:
# create an example dataframe
df=pd.DataFrame(dict(a=[1, 2, 3, 4, 5, 6], b=list('abbcac')))
df.loc[[2, 4, 5], 'c']= list('xyz')
df.loc[[2, 3, 4], 'd']= list('vxw')
df.loc[[1, 2], 'e']= list('qw')
它看起来像这样:
Out[58]:
a b c d e
0 1 a NaN NaN NaN
1 2 b NaN NaN q
2 3 b x v w
3 4 c NaN x NaN
4 5 a y w NaN
5 6 c z NaN NaN
如果你在这个数据帧上执行上面的代码,你会得到一个包含以下内容的字典:
0: a b c d e
2 3 b x v w
1: a b c d e
4 5 a y w NaN
2: a b c d e
1 2 b NaN NaN q
3 4 c NaN x NaN
5 6 c z NaN NaN
3: a b c d e
0 1 a NaN NaN NaN
字典的键是行中 s 的数量,NaN
值是数据帧,其中仅包含具有该数量NaN
s 的行。
推荐阅读
- android - Firebase电话号码认证,每次验证码都过期
- python - 谷歌 aiy 视觉套件编译器:从 tensorboard 获取输出节点
- reactjs - Azure 应用服务上的符号链接上的 yarn EPERM(不允许操作)
- java - 为什么客户端在使用 Netty 不断地从服务器获取图像时会阻塞?
- php - 如何使用codeigniter中的不同提交按钮从同一表单调用不同的函数?
- mongodb - MongoDb:如何从 .gz 文件导入转储数据?
- html - 在行下方添加元素
- windows - 如何批量获取另一个驱动器的当前工作目录?
- android - PreferenceActivity:getFragmentManager() 已被弃用
- sql - 如何在sql server的存储过程中为单个参数传递更多值