各グループの後に空白行とインデックス付きの行を挿入する方法を理解しようとしています。空白行を挿入する方法はできましたが(SOの参照のおかげで)、インデックスを使用して別の行を挿入する方法を理解するのに問題があります。
元の:
+ ------ + --------- + ------- +-+ | id | 国| スコア| | + ------ + --------- + ------- +-+ | 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 | | + ------ + --------- + ------- +-+
空白行を1つ挿入します
+ ------ + --------- + ------- + | id | 国| スコア| + ------ + --------- + ------- + | 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 | 国| スコア| + ------ + --------- + ------- + | 1011 | JPN | 5 | | 1011 | JPN | 5 | | 1011 | NZ | 4 | | 1011 | NZ | 5 | | | | | | id | 国| スコア| | 1012 | NZ | 5 | | 1012 | オフ| 6 | | 1012 | NZ | 6 | | | | | | id | 国| スコア| | 1013 | オフ| 5 | | 1013 | オフ| 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
すると、最後の2行をiloc
次の方法で最後に削除できます。
df2 = pd.DataFrame([[''] * len(df.columns), df.columns], columns=df.columns)
df1= (df.groupby('id', group_keys=False)
.apply(lambda d: d.append(df2))
.iloc[:-2]
.reset_index(drop=True))
print (df1)
id country score
0 1011 JPN 5
1 1011 JPN 5
2 1011 NZ 4
3 1011 NZ 5
4
5 id country score
6 1012 NZ 5
7 1012 AUS 6
8 1012 NZ 6
9
10 id country score
11 1013 AUS 5
12 1013 AUS 5
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加