我想知道如何在每组后面插入一个空行和一个带索引的行。 我能够插入一个空行(感谢上面的引用),但是,我很难想出如何插入另一个带有索引的行
原件:
+------+---------+-------+--+ | id | country | score | | +------+---------+-------+--+ | 1011 | JPN | 5 | | | 1011 | JPN | 5 | | | 1011 | NZ | 4 | | | 1011 | NZ | 5 | | | 1012 | NZ | 5 | | | 1012 | AUS | 6 | | | 1012 | NZ | 6 | | | 1013 | AUS | 5 | | | 1013 | AUS | 5 | | +------+---------+-------+--+
插入一个空行
+------+---------+-------+ | id | country | score | +------+---------+-------+ | 1011 | JPN | 5 | | 1011 | JPN | 5 | | 1011 | NZ | 4 | | 1011 | NZ | 5 | | | | | | 1012 | NZ | 5 | | 1012 | AUS | 6 | | 1012 | NZ | 6 | | | | | | 1013 | AUS | 5 | | 1013 | AUS | 5 | +------+---------+-------+
所需输出:
+------+---------+-------+ | id | country | score | +------+---------+-------+ | 1011 | JPN | 5 | | 1011 | JPN | 5 | | 1011 | NZ | 4 | | 1011 | NZ | 5 | | | | | | id | country | score | | 1012 | NZ | 5 | | 1012 | AUS | 6 | | 1012 | NZ | 6 | | | | | | id | country | score | | 1013 | AUS | 5 | | 1013 | AUS | 5 | +------+---------+-------+
原始DF:
import pandas as pd
import numpy as np
data = {'id':[1011,1011,1011,1011,1012,1012,1012,1013,1013],
'country':[JPN,JPN,NZ,NZ,NZ,AUS,NZ,AUS,AUS]
,'score':[5,5,4,5,5,6,6,5,5]}
df = pd.DataFrame(data)
插入空行的DF:
df1= df.groupby('id').apply(lambda d: d.append({'id': d.name}, ignore_index=True).astype({'id': int})).reset_index(drop=True)
非常感谢 问候
通过添加自定义
DataFrame
,可以通过iloc
最后删除最后2行:不是最有效的方法:
输出:
相关问题 更多 >
编程相关推荐