[英]Get one or more column values as a list from Pandas Dataframe
For the given dataframe
对于给定的
dataframe
Bin1 Bin2 Bin3
0 A 1 7
1 B 2 8
2 C 3 9
I want a list of values from Bin1
and Bin3
columns 我想从值列表
Bin1
和Bin3
列
I tried, 我试过了,
df[["Bin1","Bin3"]].values.tolist()
But it is not giving the expected list. 但这并没有给出预期的清单。
My desired output is, 我想要的输出是
output_df = ["A","B","C",7,8,9]
Here you go: 干得好:
df['Bin1'].tolist() + df['Bin3'].tolist()
['A', 'B', 'C', 7, 8, 9]
Create list of lists and then flatten : 创建列表列表,然后展平 :
l = df[["Bin1","Bin3"]].values.T.tolist()
flat_list = [item for sublist in l for item in sublist]
print (flat_list)
['A', 'B', 'C', 7, 8, 9]
Similar, thanks Bharath shetty : 相似,谢谢Bharath shetty :
flat_list = df[["Bin1","Bin2"]].values.T.flatten().tolist()
Few other ways 其他几种方法
Option 1 unstack
选项1
unstack
In [1413]: df[['Bin1', 'Bin3']].unstack().values.tolist()
Out[1413]: ['A', 'B', 'C', 7L, 8L, 9L]
Option 2 ravel
选项2
ravel
In [1426]: df[['Bin1', 'Bin3']].values.ravel(order='A')
Out[1426]: array(['A', 'B', 'C', 7L, 8L, 9L], dtype=object)
Timings 时机
In [1446]: df.shape
Out[1446]: (60000, 3)
In [1447]: %timeit df['Bin1'].values.tolist() + df['Bin3'].values.tolist()
100 loops, best of 3: 2.95 ms per loop
In [1440]: %timeit df['Bin1'].tolist() + df['Bin3'].tolist()
100 loops, best of 3: 4.87 ms per loop
In [1442]: %timeit df[['Bin1', 'Bin3']].values.ravel(order='A').tolist()
100 loops, best of 3: 5.86 ms per loop
In [1443]: %timeit df[['Bin1', 'Bin3']].unstack().values.tolist()
100 loops, best of 3: 9.32 ms per loop
In [1444]: %timeit df[["Bin1","Bin2"]].values.T.flatten().tolist()
100 loops, best of 3: 6.91 ms per loop
In [1445]: %timeit [it for subl in df[["Bin1","Bin3"]].values.T.tolist() for it in subl]
10 loops, best of 3: 20.3 ms per loop
By using melt
通过
melt
df[['Bin1','Bin3']].melt().value.tolist()
Out[382]: ['A', 'B', 'C', 7, 8, 9]
就像这样简单: list(df[["Bin1","Bin2"]].as_matrix().flatten())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.