简体   繁体   中英

How to select the first elements stored in a list of tuples?

I need to extract/clear values stored in a list of tuples, keeping only the first (left) record for each element in parentheses.

I'll put the current tables and how I need the information so it's easier to see the problem.

Current df:

ID chords
1 [(N, 0.371519274), (A7, 0.464399092)]
2 [(N, 0.371519274), (Em, 0.464399092)]

Desired df:

ID chords
1 N, A7
2 N, Em

Is this desired df possible?

Assuming the values of chords column are lists of tuples

df['chords'] = df['chords'].map(lambda lst: ", ".join(tup[0] for tup in lst))
df['chords'] = df['chords'].astype('str').str.split(r'[\[\](), ]+').apply(lambda x: (x[1], x[3]))

Output:

>>> df
   ID   chords
0   1  (N, A7)
1   2  (N, Em)
df['chords'] = df['chords'].str.extract('\(([^,]+).+\(([^,]+)').apply(tuple, axis=1)
print(df)
   ID   chords
0   1  (N, A7)
1   2  (N, Em)

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