Skip to content

Commit

Permalink
utility command to pivot a CSV
Browse files Browse the repository at this point in the history
helpful for turning CSVs with multuple rows per constituency into ones
with multuple columns per constituency
  • Loading branch information
struan committed Nov 28, 2024
1 parent ccc7b36 commit e3129e7
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions hub/management/commands/pivot_csv.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import json

from django.conf import settings
from django.core.management.base import BaseCommand

import pandas as pd


class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
"--infile",
action="store",
help="File to process",
)

parser.add_argument(
"--outfile",
action="store",
help="File to output to",
)

parser.add_argument(
"--column",
action="store",
help="Column to pivot on",
)

parser.add_argument(
"--value_column",
action="store",
help="Column with values",
)

parser.add_argument(
"--index",
action="store",
help="Column with index",
)

def handle(self, *args, **kwargs):
df = pd.read_csv(settings.BASE_DIR / "data" / kwargs["infile"])
df = df.pivot(
columns=kwargs["column"],
values=kwargs["value_column"],
index=kwargs["index"],
)
df.to_csv(settings.BASE_DIR / "data" / kwargs["outfile"])

0 comments on commit e3129e7

Please sign in to comment.