给定代表列名的下列列表:
names = [['a','b'],['c','c'],['b','c']]和下面的数据文件
df
a b c
0 1 2 6
1 1 3 2
2 4 6 4我希望生成具有以下功能的与names具有相同维度的列表:
lst = []
for idx, cols in enumerate(names):
lst.append([])
for col in cols:
lst[-1].append(df.iloc[idx][col])
lst:
[[1,2],[2,2],[6,4]也就是说,names数组指向相关row_idx中从df中提取的列。
我试图避免嵌套循环。
发布于 2022-07-02 12:04:16
可以使用列表选择多个列。
lst = []
for idx, cols in enumerate(names):
lst.append(df.iloc[idx][cols].tolist())
# or list comprehension
lst = [df.iloc[idx][cols].tolist() for idx, cols in enumerate(names)]print(lst)
[[1, 2], [2, 2], [6, 4]]发布于 2022-07-02 16:11:07
正如您所说的,names的长度与dataframe长度相同,您不希望在names上循环,也不想执行嵌套循环。在这种情况下,是否允许在range上循环?
index = range(len(names))
[df.iloc[i][names[i]].tolist() for i in index]
Out[16]: [[1, 2], [2, 2], [6, 4]]或df.loc
[df.loc[i,names[i]].tolist() for i in index]
Out[35]: [[1, 2], [2, 2], [6, 4]]https://stackoverflow.com/questions/72838864
复制相似问题