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

Time:11-26

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?

CodePudding user response:

Assuming the values of chords column are lists of tuples

df['chords'] = df['chords'].map(lambda lst: ", ".join(tup[0] for tup in lst))

CodePudding user response:

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

CodePudding user response:

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)
  • Related