简体   繁体   中英

Python loop through tuple list adding a value from pandas data frame

I am trying to loop through a list of tuples adding a value to the end of each one that corresponds to a value in a column in a pandas data frame.

df1 = [(1,2),(4,5),(8,9)]

df2 = pd.DataFrame({'Alpha': [2, 4, 8],
                    'Beta': ["a","b","c"]})

df3 = []

for i in df1:
    print(i)

for i,j in df2["Beta"], df1:
    j = j + (i,)
    df3.append(j)

print(df3)

I would expect print(df3) to display the following:

[(1, 2, 'a'), (4, 5, 'b'), (8, 9, 'c')]

However, I get an error stating too many values to unpack.

Use zip , list comprehension solution:

df3 = [j + (i,) for i,j in zip(df2["Beta"], df1)]

Your solution should be changed:

for i,j in zip(df2["Beta"], df1):
    j = j + (i,)
    df3.append(j)

print(df3)
[(1, 2, 'a'), (4, 5, 'b'), (8, 9, 'c')] 

One way using a list comprehension would be:

[(*i, j) for i, j in zip(df1,  df2.Beta)]
# [(1, 2, 'a'), (4, 5, 'b'), (8, 9, 'c')]

Or you could also map with operator.add :

from operator import add
list(map(add, df1, df2.Beta.map(tuple)))
# [(1, 2, 'a'), (4, 5, 'b'), (8, 9, 'c')]

Or working from pandas:

(pd.Series(df1) + df2.Beta.map(tuple)).values.tolist()
# [(1, 2, 'a'), (4, 5, 'b'), (8, 9, 'c')]

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