Seite 1 von 1

Prozentspalte anhand Timestamp

Verfasst: Freitag 12. Februar 2021, 21:56
von Omm
Hallo zusammen

ich möchte gerne eine Spalte haben, in der der Prozentuale Anteil ersichtlich ist. D.h. aus der Summe von Duration.
Gibt es da in pandas eine einfache Funktion.

Die Spalte mit den Zeiten ist eine timedelta64

Code: Alles auswählen

 1   Duration  timedelta64[ns]
           Duration
0  0 days 01:00:27
1  1 days 00:04:08
2  0 days 07:37:45
3  0 days 01:00:57
4  0 days 14:19:02
5  0 days 00:01:07
6  0 days 04:58:13
...

Im Ansatz sowas:
data['percentage'] = data.apply(_percentage, axis=1)
        def _percentage(x):
            pct = float(x / data[self.DURATION].sum()) * 100
            return round(pct, 2)
Muss ich aus der Duration Spalte eine neue mit int Werten erstellen?

Code: Alles auswählen

           Duration      Prozentanteil
0  0 days 01:00:27       xx%
1  1 days 00:04:08       xx% 
2  0 days 07:37:45       xx%
3  0 days 01:00:57       xx%
4  0 days 14:19:02       xx%
5  0 days 00:01:07       xx%
6  0 days 04:58:13       xx%

Re: Prozentspalte anhand Timestamp

Verfasst: Samstag 13. Februar 2021, 10:23
von Omm
ich habe es jetzt so gelöst. evtl. gibt es ja eine bessere Lösung.

Code: Alles auswählen

        data['durationSeconds'] = data[self.DURATION].dt.total_seconds()
        data['Prozentanteil'] = data['durationSeconds'].transform(lambda x: 100 * x / x.sum())
 

Re: Prozentspalte anhand Timestamp

Verfasst: Samstag 13. Februar 2021, 10:48
von Sirius3
transform habe ich noch nie benutzt. Einen neuen DataFrame brauchst du hier auch gar nicht.

Code: Alles auswählen

        data['durationSeconds'] = data[self.DURATION].dt.total_seconds()
        data['Prozentanteil'] = data['durationSeconds'] * (100 / data['durationSeconds'].sum())

Re: Prozentspalte anhand Timestamp

Verfasst: Samstag 13. Februar 2021, 11:31
von Omm
@Sirius3 Vielen Dank für die Hilfe. Diese Lösung ist wesentlich besser.