简体   繁体   English

如何将 select 的第一个元素存储在元组列表中?

[英]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:当前df:

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

Desired df:所需的df:

ID ID chords和弦
1 1 N, A7 N, A7
2 2 N, Em N, 埃姆

Is this desired df possible?这可能是所需的 df 吗?

Assuming the values of chords column are lists of tuples假设chords列的值是元组列表

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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