-1

I have a variable that stores a single list of tuples.

It looks like this:

builddict =  [
    ('MfgPartNumber', 'ITEM NUMBER'), 
    ('ShortDescription', 'ITEM DESCRIPTION'), 
    ('StdPk', 'PACKAGE QTY'), 
    ('ListPrice', 'LIST PRICE'), 
    ('Cost', 'NET PRICE APRIL 2024')
]

It is dynamically created based on a loop, so the values will vary by output.

I would like to take that list and build a dataframe from it with the first item as the column name, and the second item and the corresponding row.

For Example:

| MfgParNumber | ShortDescription   | StdPk |
| ------------ | ------------------- |----- |
| ITEM NUMBER  | ITEM DESCRIPTION   |PACKAGE QTY|  etc...

I tried this, but can't figure out how to apply the column names to it:

DictCols = list(zip(*builddict))[0]
DictData = pd.DataFrame(list(zip(*builddict))[1]).T
print(DictData)
4
  • Does this answer your question? Constructing DataFrame from values in variables yields "ValueError: If using all scalar values, you must pass an index" Commented Jun 6, 2024 at 22:59
  • "I tried this, but can't figure out how to apply the column names to it:" What happens when you try that, and how is that different from what you want? Commented Jun 6, 2024 at 23:38
  • To be clear: you want the result DataFrame to only ever have one row of data (and a header)? Exactly what is the use of this result? Commented Jun 6, 2024 at 23:40
  • Think about how you'd want the data to be structured to create the DataFrame you want normally, then do all the data rearrangement first. Commented Jun 6, 2024 at 23:47

2 Answers 2

-1

For the data row, you need to put it in another list. Then pass the list of column names as the columns argument.

cols, data = zip(*builddict)
df = pd.DataFrame([data], columns=cols)
Sign up to request clarification or add additional context in comments.

Comments

-1

You could convert the tuple to a list of dicts by:

build_dict = [{k: v for k, v in builddict}]

and then create a dataframe from this dict

build_df = pd.DataFrame(build_dict)

That should work for a variable length list of tuples.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.