我有以下几种类型的多索引数据框:
import random
col3=[0,0,0,0,2,4,6,0,0,0,100,200,300,400]
col4=[0,0,0,0,4,6,8,0,0,0,200,900,400, 500]
d = {'Unit': [1, 1, 1, 1, 2, 2, 2, 3, 4, 5, 6, 6, 6, 6],
'Year': [2014, 2015, 2016, 2017, 2015, 2016, 2017, 2017, 2014, 2015, 2014, 2015, 2016, 2017], 'col3' : col3, 'col4' : col4 }
df = pd.DataFrame(data=d)
new_df = df.groupby(['Unit', 'Year']).sum()
col3 col4
Unit Year
1 2014 0 0
2015 0 0
2016 0 0
2017 0 0
2 2015 2 4
2016 4 6
2017 6 8
3 2017 0 0
4 2014 0 0
5 2015 0 0
6 2014 100 200
2015 200 900
2016 300 400
2017 400 500
实际上,这当然更大,但这确实可以做到。在此数据框中,我要删除所有只有一年条目的单位。所以我想要这个:
col3 col4
Unit Year
1 2014 0 0
2015 0 0
2016 0 0
2017 0 0
2 2015 2 4
2016 4 6
2017 6 8
6 2014 100 200
2015 200 900
2016 300 400
2017 400 500
预先感谢您的帮助,
Jen
答案 0 :(得分:6)
将GroupBy.transform
与任何列一起使用,并将测试计数与GroupBy.size
进行比较,用Series.ne
进行比较,并用boolean indexing
进行过滤:
df = new_df[new_df.index.get_level_values(0).duplicated(keep=False)]
或者通过Index.get_level_values
获取索引值,并通过Index.duplicated
进行过滤:
print (df)
col3 col4
Unit Year
1 2014 0 0
2015 0 0
2016 0 0
2017 0 0
2 2015 2 4
2016 4 6
2017 6 8
6 2014 100 200
2015 200 900
2016 300 400
2017 400 500
export class HomePage {
bufferSize:number = 8192;
mediaRecorder;
constructor(public socket:Socket) {}
ngOnInit(){
this.socket.connect();
window.addEventListener('audioinput', (data) => {
this.onAudioInput(data, this.socket);
});
audioinput.initialize({
sampleRate: 8000,
bufferSize: this.bufferSize,
channels: 1,
format: audioinput.FORMAT.PCM_16BIT,
audioSourceType: audioinput.AUDIOSOURCE_TYPE.MIC
}, () => {
audioinput.checkMicrophonePermission((hasPermission) => {
if (hasPermission) {
console.log("Permission already exist");
}
else {
audioinput.getMicrophonePermission((hasPermission, message) => {
if (hasPermission) {
console.log("User gived permission.");
} else {
console.warn("User denied permission.");
}
});
}
});
});
}
onAudioInput(data, socket){
socket.emit("audioinput", data.data);
}
start(){
audioinput.start({
sampleRate: 8000,
bufferSize: this.bufferSize,
channels: 1,
format: audioinput.FORMAT.PCM_16BIT,
audioSourceType: audioinput.AUDIOSOURCE_TYPE.MIC
});
this.socket.emit("message", "started");
}
stop(){
audioinput.stop();
this.socket.emit("message", "stoped");
}
}