简体   繁体   中英

Get a list from a pandas dataframe

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.

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)]

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)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM