One way to do this would be to take the column names as a separate list and then only give from 1st index for pd.DataFrame -
In [8]: data = [['Name','Rank','Complete'],
...: ['one', 1, 1],
...: ['two', 2, 1],
...: ['three', 3, 1],
...: ['four', 4, 1],
...: ['five', 5, 1]]
In [10]: df = pd.DataFrame(data[1:],columns=data[0])
In [11]: df
Out[11]:
Name Rank Complete
0 one 1 1
1 two 2 1
2 three 3 1
3 four 4 1
4 five 5 1
If you want to set the first column Name column as index, use the .set_index() method and send in the column to use for index. Example -
In [16]: df = pd.DataFrame(data[1:],columns=data[0]).set_index('Name')
In [17]: df
Out[17]:
Rank Complete
Name
one 1 1
two 2 1
three 3 1
four 4 1
five 5 1
Answer from Anand S Kumar on Stack OverflowOne way to do this would be to take the column names as a separate list and then only give from 1st index for pd.DataFrame -
In [8]: data = [['Name','Rank','Complete'],
...: ['one', 1, 1],
...: ['two', 2, 1],
...: ['three', 3, 1],
...: ['four', 4, 1],
...: ['five', 5, 1]]
In [10]: df = pd.DataFrame(data[1:],columns=data[0])
In [11]: df
Out[11]:
Name Rank Complete
0 one 1 1
1 two 2 1
2 three 3 1
3 four 4 1
4 five 5 1
If you want to set the first column Name column as index, use the .set_index() method and send in the column to use for index. Example -
In [16]: df = pd.DataFrame(data[1:],columns=data[0]).set_index('Name')
In [17]: df
Out[17]:
Rank Complete
Name
one 1 1
two 2 1
three 3 1
four 4 1
five 5 1
To create the desired dataframe from construction, the list could be converted into a numpy array and indexed accordingly.
arr = np.array(data, dtype=object)
df = pd.DataFrame(arr[1:, 1:], index=pd.Index(arr[1:, 0], name=arr[0,0]), columns=arr[0, 1:], dtype=int)
Another method is, since the data looks like a csv file read into a Python list, it could be converted into an in-memory text buffer and have pd.read_csv called on it. A nice thing about read_csv is that it can set MultiIndex columns, indices etc. and can infer dtypes.
from io import StringIO
df = pd.read_csv(StringIO('\n'.join(['|'.join(map(str, row)) for row in data])), sep='|', index_col=[0])

A convenience function for the latter method:
from io import StringIO
def read_list(data, index_col=None, header=0):
sio = StringIO('\n'.join(['|'.join(map(str, row)) for row in data]))
return pd.read_csv(sio, sep='|', index_col=index_col, header=header)
df = read_list(data, index_col=[0])
I have a nested list which I'd like to convert into a dataframe and add each list item to a new row. i've seen a few exams showing how to separate the list into different columns but none on how to keep the list together (separated by "" and , ) but add it to separate rows.
As an example
data = [['one', 1, 1], ['two', 2, 1], ['three', 3, 1]]
and output would be
| List |
|---|
| ['one', 1, 1] |
| ['two', 2, 1] |
| ['three', 3, 1] |
The reason being is i have multiple lists i want to add to the same dataframe. 1 column will be the sentences of the text. the next column is the split up words but i want it to be kept with the original sentence.
Thanks
I am working on creating a small job shop scheduler and need to convert my data from SQL table to nested lists in python.
| Order Number | process_id | machine_id | process_time | changover_time_1 | machine_id | sfg_id | rm_id |
|---|---|---|---|---|---|---|---|
| Order 1 | 1 | 11 | 720 | 90 | 11 | 179 | 37 |
| Order 1 | 1 | 12 | 360 | 90 | 12 | 142 | 55 |
| Order 1 | 2 | 13 | 360 | 90 | 13 | 46 | 55 |
| Order 1 | 3 | 15 | 720 | 90 | 15 | 180 | 8 |
| Order 2 | 1 | 11 | 240 | 90 | 11 | 68 | 8 |
| Order 2 | 2 | 13 | 720 | 90 | 13 | 43 | 24 |
| Order 2 | 2 | 14 | 600 | 90 | 14 | 175 | 4 |
| Order 2 | 3 | 16 | 480 | 90 | 16 | 172 | 40 |
| Order 2 | 3 | 15 | 480 | 90 | 15 | 209 | 40 |
There are two levels in this table. First is process_id where a single order can be executed on alternative machines. I need to create a list for every process stage in the order. Inside the list will be a tuple of form (machine_id, process_time, changeover_time_1, machine_id, sfg_id, rm_id).
The output will look something like this:
| Order Number | process_id | tuple 2 |
|---|---|---|
| Order 1 | 1 | (11,720,90,11,179), (12,360,90,12,142) |
| Order 1 | 2 | (13,360,90,13,46) |
| Order 1 | 3 | (15,720,90,15,180) |
| Order 2 | 1 | (11,240,90,11,68) |
| Order 2 | 2 | (13,720,90,13,43), (14,600,90,14,175) |
| Order 2 | 3 | (16,480,90,16,172), (15,480,90,15,209) |
Now the all the processes inside the order are included as lists inside a list for every order. The output will look something like this:
| Order Number | tuple 3 |
|---|---|
| Order 1 | [(11,720,90,11,179), (12,360,90,12,142)], [(13,360,90,13,46)], [(15,720,90,15,180)] |
| Order 2 | [(11,240,90,11,68)], [(13,720,90,13,43), (14,600,90,14,175)], [(16,480,90,16,172), (15,480,90,15,209)] |
I have tried using df.values.tolist() but I can't get the nested lists. I have also tried to convert it into the dictionary and create tuples. It only works for a single stage of the process but I can't think of how to make it work for multiple stages. Previous attempt here
Here's one way using itertools, given input list L:
from itertools import chain, product, repeat
col, value = zip(*(list(i) for item in L for i in product(item[1], item[2])))
cat = list(chain.from_iterable(repeat(i, len(j) * len(k)) for i, j, k in L))
df = pd.DataFrame({'Cat': cat, 'Column': col, 'Value': value})
df = df.sort_values(['Cat', 'Column', 'Value']).reset_index(drop=True)
print(df)
Cat Column Value
0 R1 a 20.0
1 R1 a 40.0
2 R1 a 50.0
3 R1 a 60.0
4 R1 a 750.0
5 R1 b 20.0
...
39 R3 x 10.0
40 R3 x 12.5
41 R3 x 45.0
First create list from first element and then expand by product, also added sorted if necessary:
from itertools import product
L = [[[x[0]], sorted(x[1]), sorted(x[2])] for x in nested_list]
df1 = pd.DataFrame([j for i in L for j in product(*i)], columns=['Cat','Column','Value'])
print (df1.head(20))
Cat Column Value
0 R1 a 20.0
1 R1 a 40.0
2 R1 a 50.0
3 R1 a 60.0
4 R1 a 750.0
5 R1 b 20.0
6 R1 b 40.0
7 R1 b 50.0
8 R1 b 60.0
9 R1 b 750.0
10 R1 c 20.0
11 R1 c 40.0
12 R1 c 50.0
13 R1 c 60.0
14 R1 c 750.0
15 R2 x 35.0
16 R2 x 37.5
17 R2 x 165.0
18 R2 y 35.0
19 R2 y 37.5
I would like a command to transform a nested list into a dataframe , for instance
p=[[0, 4, 1, 2, 3], [0.0, 0.0, 4.760181427001953, 5.195466041564941, 5.243175506591797]]
with the result looking something like this table
| index | pos | score |
|---|---|---|
| 0 | 0 | 0.0 |
| 1 | 4 | 0.0 |
| 2 | 1 | 4.760181427001953 |
| 3 | 2 | 5.195466041564941 |
| 4 | 3 | 5.243175506591797 |
Hello, I'm a Reddit bot who's here to help people nicely format their coding questions. This makes it as easy as possible for people to read your post and help you.
I think I have detected some formatting issues with your submission:
-
Python code found in submission text that's not formatted as code.
If I am correct, please edit the text in your post and try to follow these instructions to fix up your post's formatting.
Am I misbehaving? Have a comment or suggestion? Reply to this comment or raise an issue here.
I think youโre looking for the df.transpose() method?
Hi all, I'm new to Python and have been struggling with the response from a REST API, so looking for some help from the pros.
I've created a simplified version of the json structure below but it's nested lists within lists within a list
data = { "status": 200,
"errmsg": "OK",
"data": { "total": 2,
"items": [{ "id": 1,
"displayname": "name1",
"type": "type1",
"properties": [ { "name": "property1", "value": "value1" },
{ "name": "property2", "value": "value2" }],
"details": [ { "name": "detail1", "value": "value1" },
{ "name": "detail2", "value": "value2" },
{ "name": "detail3", "value": "value3" }]},
{ "id": 2,
"displayname": "name2",
"type": "type2",
"properties": [ { "name": "property1", "value": "value1" },
{ "name": "property2", "value": "value2" }],
"details": [ { "name": "detail1", "value": "value1" },
{ "name": "detail2", "value": "value1" }]
}]
}
}I need an output that looks like the below:
| displayname | type | property2 | detail1 | detail3 |
|---|---|---|---|---|
| name1 | type1 | value2 | value1 | value3 |
| name2 | type2 | value2 | value1 | NaN |
And I've made some progress with this:
import pandas as pd properties = pd.json_normalize(data['data']['items'], record_path='properties', meta=['displayname','type']) df = pd.DataFrame(properties) filter = df.loc[df['name'] == 'property2'] pivot = filter.pivot(index=['displayname','type'], columns='name', values='value') print(pivot)
Which gets me to:
| displayname | type | property2 |
|---|---|---|
| name1 | type1 | value2 |
| name2 | type2 | value2 |
That's half the job as I've managed to get the columns from the meta level, and then the single column I want from the 'properties' list, but because I've specified the relative_path in json.normalize to be 'properties', I can't get the columns I need from 'details'.
I could duplicate my code and change the relative path to 'details' but there's an extra layer of complication here in that I want to create two columns from the values found in 'details' - detail 1 & detail 3 - but detail 3 only exists for one of the records, so I would expect a NaN there (I think)?
NOTE: In my real json response, there's 320 records, of which not all of them will have a 'property' or 'detail' that I'm looking for, but I still want all 320 records (displaynames) to appear in my dataframe.
Can anyone offer any tips or advice on how can get this across the finish line?
Thank you in advance!
I think the simple will remain for loops.
First, select all keys from the given
features.- For all elements, we use
str.splitand extract the first element. - Then, because we only want unique keys, we use
set. Then, we convert it back tolistand sort the keys usingsorted(here some details if needed).
- For all elements, we use
The first is sum up in:
keys = sorted(list(set([elt.split(':')[0] for l in features for elt in l])))
- Create an empty
dictfrom the above keys and initialize all keys with an empty list:
data = {k:[] for k in keys}
Iterate over all the features:
- Save all the key features visited in a
seenvariable - Add all featured keys and values
- Complete the data with keys not in the current
features
- Save all the key features visited in a
Eventually, create the dataframe from out dict using the default constructor [
pd.DataFrame()] (https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html).Correctly format columns name using
.columnsand string formatting (format). Here are some good explanations.
Talked enough, here the full code + illustration:
features = [["0:0.084556", "1:0.138594", "2:0.094304"],
["0:0.101468", "4:0.138594", "5:0.377215"],
["0:0.135290", "2:0.277187", "3:0.141456"]
]
# Step 1
keys = sorted(list(set([elt.split(':')[0] for l in features for elt in l])))
print(keys)
# ['0', '1', '2', '3', '4', '5']
# Step 2
data = {k:[] for k in keys}
print(data)
# {'0': [], '1': [], '2': [], '3': [], '4': [], '5': []}
# Step 3
for sub in features:
# Step 3.1
seen = []
# Step 3.2
for l in sub:
k2, v = l.split(":") # Get key and value
data[k2].append(float(v)) # Append current value to data
seen.append(k2) # Set the key as seen
# Step 3.3
for k in keys: # For all data keys
if k not in seen: # If not seen
data[k].append(0) # Add 0
print(data)
# {'0': [0.084556, 0.101468, 0.13529],
# '1': [0.138594, 0, 0],
# '2': [0.094304, 0,0.277187],
# '3': [0, 0, 0.141456],
# '4': [0, 0.138594, 0],
# '5': [0, 0.377215, 0]
# }
# Step 4
df = pd.DataFrame(data)
print(df)
# 0 1 2 3 4 5
# 0 0.084556 0.138594 0.094304 0.000000 0.000000 0.000000
# 1 0.101468 0.000000 0.000000 0.000000 0.138594 0.377215
# 2 0.135290 0.000000 0.277187 0.141456 0.000000 0.000000
# Step 5
df.columns = ["f_{:04d}".format(int(val)) for val in df.columns]
print(df)
# f_0000 f_0001 f_0002 f_0003 f_0004 f_0005
# 0 0.084556 0.138594 0.094304 0.000000 0.000000 0.000000
# 1 0.101468 0.000000 0.000000 0.000000 0.138594 0.377215
# 2 0.135290 0.000000 0.277187 0.141456 0.000000 0.000000
try this:
df = pd.DataFrame(data, columns = ['Column name 1'], ['column name 2'])