Ich habe ein Problem mit der Methode apply () des Pandas DataFrame. Mein Problem ist, dass Apply () je nach Rückgabetyp der Eingabefunktion entweder eine Serie oder einen Datenrahmen zurückgeben kann. Wenn der Rahmen jedoch leer ist, gibt () (fast) immer einen Datenrahmen an. Ich kann also keinen Code schreiben, der eine Serie erwartet. Hier ist ein Beispiel: < /p>
import pandas as pd
def area_from_row(row):
return row['width'] * row['height']
def add_area_column(frame):
# I know I can multiply the columns directly, but my actual function is
# more complicated.
frame['area'] = frame.apply(area_from_row, axis=1)
# This works as expected.
non_empty_frame = pd.DataFrame(data=[[2, 3]], columns=['width', 'height'])
add_area_column(non_empty_frame)
# This fails!
empty_frame = pd.DataFrame(data=None, columns=['width', 'height'])
add_area_column(empty_frame)
< /code>
Gibt es eine Standardmethode, um damit umzugehen? Ich kann Folgendes machen, aber es ist albern: < /p>
def area_from_row(row):
# The way we respond to an empty row tells pandas whether we're a
# reduction or not.
if not len(row):
return None
return row['width'] * row['height']
< /code>
(Ich verwende Pandas 0.11.0, aber ich habe dies auch auf 0.12.0-1100-g0C30665 überprüft.) < /p>
Anrufen anwenden () auf einem leeren Pandas -Datenframe ⇐ Python
-
- Similar Topics
- Replies
- Views
- Last post
-
-
Wie löste ich Speicher frei, das von einem Pandas -Datenframe verwendet wird?
by Anonymous » » in Python - 0 Replies
- 0 Views
-
Last post by Anonymous
-