Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

324
Views
¿Cómo reordenar filas en el marco de datos de pandas por nivel de factor en python?

Creé un pequeño conjunto de datos que compara los precios de las bebidas de café por tamaño de taza.

Cuando giro mi conjunto de datos, la salida reordena automáticamente el índice (la columna 'Tamaño') alfabéticamente.

¿Hay alguna manera de asignar un nivel numérico a los diferentes tamaños (por ejemplo, pequeño = 0, mediano = 1, grande = 2) y reordenar las filas de esta manera?

Sé que esto se puede hacer en R usando la biblioteca forcats (usando fct_relevel por ejemplo), pero no sé cómo hacerlo en python. Preferiría mantener la solución para usar numpy y pandas.

 data = {'Item': np.repeat(['Latte', 'Americano', 'Cappuccino'], 3), 'Size': ['Small', 'Medium', 'Large']*3, 'Price': [2.25, 2.60, 2.85, 1.95, 2.25, 2.45, 2.65, 2.95, 3.25] } df = pd.DataFrame(data, columns = ['Item', 'Size', 'Price']) df = pd.pivot_table(df, index = ['Size'], columns = 'Item') df # Price # Item Americano Cappuccino Latte # Size # Large 2.45 3.25 2.85 # Medium 2.25 2.95 2.60 # Small 1.95 2.65 2.25
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Puede usar un tipo Categorical con ordered=True :

 df.index = pd.Categorical(df.index, categories=['Small', 'Medium', 'Large'], ordered=True) df = df.sort_index()

producción:

 Price Item Americano Cappuccino Latte Small 1.95 2.65 2.25 Medium 2.25 2.95 2.60 Large 2.45 3.25 2.85

Puedes acceder a los códigos con:

 >>> df.index.codes array([0, 1, 2], dtype=int8)

Si esto fuera una Serie:

 >>> series.cat.codes
over 4 years ago · Santiago Trujillo Report

0

Una opción es crear el categórico, antes de pivotar; para este caso, estoy usando encode_categorical de pyjanitor , principalmente por conveniencia:

 # pip install pyjanitor import pandas as pd import janitor (df .encode_categorical(Size = (None, 'appearance')) .pivot_table(index='Size', columns='Item') ) Price Item Americano Cappuccino Latte Size Small 1.95 2.65 2.25 Medium 2.25 2.95 2.60 Large 2.45 3.25 2.85

De esta manera, no tiene que preocuparse por clasificar, ya que pivotar implícitamente hace eso. Puede omitir el pyjanitor y limitarse a Pandas solamente:

 (df .astype({'Size': pd.CategoricalDtype(categories = ['Small', 'Medium', 'Large'], ordered = True)}) .pivot_table(index='Size', columns='Item') ) Price Item Americano Cappuccino Latte Size Small 1.95 2.65 2.25 Medium 2.25 2.95 2.60 Large 2.45 3.25 2.85
over 4 years ago · Santiago Trujillo Report

0

1er CAMINO:

La función pivot_table ordena las filas según el índice. Por lo tanto, es mejor usar la función lambda cuando se aplica el índice en la función pivot_table. De esta manera, no necesita más pasos de clasificación (más tiempo) ni ninguna biblioteca de terceros.

 df = pd.pivot_table(df, index = (lambda row: 0 if df.loc[row,'Size']=="Small" else 1 if df.loc[row,'Size']=="Medium" else 2), columns = 'Item') Price Item Americano Cappuccino Latte 0 1.95 2.65 2.25 1 2.25 2.95 2.60 2 2.45 3.25 2.85

2do CAMINO:

También puede usar su propio código y luego cambiar el nombre y ordenar la tabla recién creada:

 df = pd.DataFrame(data, columns = ['Item', 'Size', 'Price']) df = pd.pivot_table(df, index = ['Size'], columns = 'Item') # rename: df = df.rename(index= lambda x: 0 if x=="Small" else 1 if x=="Medium" else 2) #sort: df = df.sort_index(ascending = True) Price Item Americano Cappuccino Latte 0 1.95 2.65 2.25 1 2.25 2.95 2.60 2 2.45 3.25 2.85
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!