![](/img/trans.png)
[英]how to aggregate elements of a list of tuples if the tuples have the same first element?
[英]How to select the first elements stored in a list of tuples?
我需要提取/清除存储在元组列表中的值,只保留括号中每个元素的第一个(左)记录。
我将放置当前表格以及我如何需要这些信息,以便更容易看到问题。
当前df:
ID | 和弦 |
---|---|
1 | [(N, 0.371519274), (A7, 0.464399092)] |
2 | [(N, 0.371519274), (Em, 0.464399092)] |
所需的df:
ID | 和弦 |
---|---|
1 | N, A7 |
2 | N, 埃姆 |
这可能是所需的 df 吗?
假设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:
>>> 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.