Reputation: 165
I would want to get a list from the columns of this pandas dataframe (all together):
So that I could have something like --> list = (x, y, value)
list=((0,0,2986),(0,1,2992)...)
I have seen some examples of getting a list from a dataframe but I don't know how to get a list such as that kind of list.
Upvotes: 1
Views: 135
Reputation: 6748
import pandas as pd
df = pd.DataFrame([[(1,1),2],[(1,1),2],[(1,1),2]],columns=['a','b'])
records = list(df.itertuples(index=False, name=None)) # get all records you can only consider required columns here
final_list = [row[0]+(row[1],) for row in records] # add all 3 elements into one tuple
print(final_list)
Out:
[(1, 1, 2), (1, 1, 2), (1, 1, 2)]
Upvotes: 2
Reputation: 27946
import pandas as pd
df = pd.DataFrame({
"y": [5, 6, 7, 8],
"x": [1, 2, 3, 4],
"value": [10, 11, 12, 13]
})
np_values = df[["x", "y", "value"]].values
values_list = [tuple(np_values[i]) for i in range(np_values.shape[0])]
print(values_list)
prints
[(1, 5, 10), (2, 6, 11), (3, 7, 12), (4, 8, 13)]
Upvotes: 2