简体   繁体   中英

How to generate an array of paired tuples from a dataframe in python?

I have a data frame that contains two columns, one of them contains a sender and the other receiver, example bellow:

https://i.stack.imgur.com/QsT38.png

I am attempting to convert this into an array that contains paired tuples, for example [(1,141),(1,125),...,(149,29)], without manually inputting each of the pairs. I understand how to automatically add elements if this were a regular array, but I don't know how I would do it for tuples.

It's a bit tricky to answer your question because I don't have enought elements (is your dataframe only have 2 columns?)

if yes, the answer looks like this:

import pandas as pd

# Create a dataframe
d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)

# use to records to convert dataframe to a record np.array
records = df.to_records(index=False)
# convert to list
result = list(records)
print(result)

it'll give you the result you want ONLY if you have a two columns dataframe.

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