Pandas wide_to_long,id变量需要唯一标识每一行

时间:2018-06-14 11:11:54

标签: python pandas dataframe

假设我有一个像这样的数据框

ID,Time1,Value1,Time2,Value2,Time3,Value3
1,2,1.1,3,1.2,4,1.3
1,5,2.1,6,2.2,7,2.3

预期的数据框就是这个

ID,Time,Value
1,2,1.1
1,3,1.2
1,4,1.3
1,5,2.1
1,6,2.2
1,7,2.3

如果该行具有唯一ID,则pd.wide_to_long在这种情况下可以正常工作。

df = pd.wide_to_long(df, ['Time',Value],'ID','value', sep='', suffix='.+')\
    .reset_index()\
    .sort_values(['ID', 'Time'])\
    .drop('value', axis=1)\
    .dropna(how='any')

但如果行的ID不是唯一的,如何解决这种情况

1 个答案:

答案 0 :(得分:3)

Trick使用reset_index作为唯一值列:

import { Component, OnInit } from '@angular/core';
import { WeatherService } from '../service/weather.service';
import { Weather } from '../model/weather';

@Component({
selector: 'weather-widget',
templateUrl: './weather.component.html',
styleUrls: ['./weather.component.css'],
providers:[WeatherService]
})

export class WeatherComponent implements OnInit{
pos : Position;
WeatherData = new Weather(null, null, null, null, null);
currentSpeedUnit = "kph";
currentTempUnit = "fahrenheit";
currentLocation = "";
constructor(private service:WeatherService){}

ngOnInit(){
    this.getCurrentLocation();

}
getCurrentLocation(){
    this.service.getCurrentLocation()
        .subscribe(position => {
            this.pos = position;
            this.getCurrentWeather();
            this.getLocationName();

        },
        err => console.error(err));
}

getCurrentWeather(){
    this.service.getCurrentWeather(this.pos.coords.latitude, this.pos.coords.longitude)
        .subscribe(weather => {
            this.WeatherData.temp = weather["currently"]["temperature"],
            this.WeatherData.summary = weather["currently"]["summary"],
            this.WeatherData.wind = weather["currently"]["windSpeed"],
            this.WeatherData.humidity = weather["currently"]["humidity"],
            this.WeatherData.icon = weather["currently"]["icon"]
            console.log("Weather:", this.WeatherData); //to remove
        },
        err => console.error(err));
}


getLocationName(){
    this.service.getLocationName(this.pos.coords.latitude, this.pos.coords.longitude)
        .subscribe(location => {
            console.log(location); //TODO: remove
        }
    );
}

<强>详细

 'Invoking: Cross ARM GNU Print Size'
arm-none-eabi-size --format=berkeley "Phaethon_F446.elf"
text       data     bss     dec     hex filename
142935      924   77140  220999   35f47 Phaethon_F446.elf