给定一个多索引DataFrame,我想组合重复的索引对并将它们的值列为逗号分隔列表。例如,输入:
df = pd.DataFrame({'Last Name' : ['Deere','Deere','Foo' ,'Foo' ,'Man' ],
'First Name': ['John' ,'Jane' ,'Kung' ,'Kung' ,'Karate'],
'Value1': [ 1 , 2 , 3 , 4 , 5 ],
'Value2': ['Green','Blue' ,'Yellow','Black','Purple']})
df.set_index(['Last Name','First Name'],inplace=True)
提供:
Value1 Value2
Last Name First Name
Deere John 1 Green
Jane 2 Blue
Foo Kung 3 Yellow
Kung 4 Black
Man Karate 5 Purple
我想将其转换为以下DataFrame:
Value1 Value2
Last Name First Name
Deere John 1 Green
Jane 2 Blue
Foo Kung 3,4 Yellow,Black
Man Karate 5 Purple
答案 0 :(得分:3)
您可以先按astype
将列Value1
转换为string
,然后Last Name
将First Name
和join
转换为groupby
} df['Value1'] = df['Value1'].astype(str)
result = df.groupby(level=['Last Name','First Name'], sort=False).agg( ','.join)
print result
Value1 Value2
Last Name First Name
Deere John 1 Green
Jane 2 Blue
Foo Kung 3,4 Yellow,Black
Man Karate 5 Purple
:
if(process.env.MONGOLAB_URI) {
mongoose.connect(process.env.MONGOLAB_URI);
} else {
mongoose.connect("mongodb://localhost/itrack");
}
global.db = mongoose;
mongoose.connection.on('open', function() {
// This line is getting printed here
console.log('Mongoose opened.');
});
// When successfully connected
mongoose.connection.on('connected', function () {
console.log('Worker ' + process.pid + ' is alive!');
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port:', app.get('port'));
});
});
// If the connection throws an error
mongoose.connection.on('error',function (err) {
console.log('Mongoose default connection error: ' + err);
process.exit(0);
});
// When the connection is disconnected
mongoose.connection.on('disconnected', function () {
console.log('Mongoose default connection disconnected');
});