Iterate through df row and append to a list w/o name and dtype

Viewed 470

I have a df that has 24 cols and I want to iterate through each row and append to a list consecutively.

Code below does the job - but it also appends on the index value and, name, and dtype, which I need to remove.

results = []
for row in data.iterrows():
    results.append(row)
(0, 1     11.87
2      7.60
3      0.32
4      3.11
5     47.43
6     47.81
7     24.74
8     32.57
9     39.49
10    24.48
11    18.14
12    26.52
13    14.17
14    13.45
15    17.80
16    17.89
17    27.39
18    51.55
19    60.22
20    69.64
21    75.97
22    67.45
23    52.88
24    53.25
Name: 0, dtype: float64)
(1, 1     54.49
2     51.67
3     53.68
4     33.81
5     26.99
6     25.80
7     36.35
8     28.85
9     26.01
10     8.44
11     1.64
12     8.01
13    23.41
14    16.22
15    16.30
16     8.90
17     1.93
18     0.00
19     2.79
20    30.24
21    55.58
22    62.79
23    74.70
24    68.46
Name: 1, dtype: float64)

It's similar to iterating through each row, transposing selected row, then adding them appending onto a list consecutively. If a df is (5, 24) then length of list will be 5*24 = 120.

2 Answers

You don't need to iterate through them. Try this:

inp = [{'c1':10, 'c2':100}, {'c1':11,'c2':110}, {'c1':12,'c2':120}]
df = pd.DataFrame(inp)

print(df)
    c1  c2
0   10  100
1   11  110
2   12  120

Now you can use .values.ravel() to create a list of all dataframe values:

list(df.values.ravel())

Output:

[10, 100, 11, 110, 12, 120]

As your question is asked you are likely want a output in tuple/list with corresponding values for each row. the output you are asking for is not a flatten list.

pandas have good funtions to actually use numpy, numpy is a great module to work with when it comes to arrays/lists.

lets say you have a DataFrame called data in this case, if you use data.to_numpy() it will actually output a nested list with values for each row.

output: 
[['joe' 'Doe' 34]
 ['bob' 'Warren' 20]
 ['Anna' 'Anderson' 10]]

you can even index your list like: data.to_numpy()[0]. you can even .flatten() your list like: data.to_numpy().flatten()

output with .flatten():

['joe' 'Doe' 34 'bob' 'Warren' 20 'Anna' 'Anderson' 10]

you can use a for loop to:

for i in data.to_numpy():
    print(i)

this give you every list in the nested list.

Related