问题描述
Click here for the image我正在尝试从3个不同系列创建一个列表,这些列表的形状将为“({{A} {B} {C})}”,其中A表示系列1中的第一个元素,B为对于系列2的第一个元素,C表示系列3的第一个元素,这样它应该创建一个包含600个元素的列表。
List 1 List 2 List 3
u_p0 1 v_p0 2 w_p0 7
u_p1 21 v_p1 11 w_p1 45
u_p2 32 v_p2 25 w_p2 32
u_p3 45 v_p3 76 w_p3 49
... .... ....
u_p599 56 v_p599 78 w_599 98
现在我想要输出列表如下
(1 2 7)
(21 11 45)
(32 25 32)
(45 76 49)
.....
这些是我根据数据框创建的3个系列
r1=turb_1.iloc[qw1] #List1
r2=turb_1.iloc[qw2] #List2
r3=turb_1.iloc[qw3] #List3
Pic of the series对于输出,我认为格式化的字符串python方法将很有用,但我不确定如何继续。
turb_3= ["({A} {B} {C})".format(A=i,B=j,C=k) for i in r1 for j in r2 for k in r3]
任何帮助都是有用的。
解决方法
将pandas.DataFrame.itertuples
与str.format
一起使用:
# Sample data
print(df)
col1 col2 col3
0 1 2 7
1 21 11 45
2 32 25 32
3 45 76 49
fmt = "({} {} {})"
[fmt.format(*tup) for tup in df[["col1","col2","col3"]].itertuples(False,None)]
输出:
['(1 2 7)','(21 11 45)','(32 25 32)','(45 76 49)']