如何在pandas数据帧中获取行列表的最小值

时间:2017-02-06 09:44:13

标签: python list pandas row min

我有一个pandas数据框,其列由列表组成。
目标是找到行中每个列表的最小值(以有效的方式)。

E.g。

import pandas as pd
df = pd.DataFrame(columns=['Lists', 'Min'])
df['Lists'] = [ [1,2,3], [4,5,6], [7,8,9] ]
print(df)

目标是Min列:

       Lists  Min
0  [1, 2, 3]  1
1  [4, 5, 6]  4
2  [7, 8, 9]  7

提前谢谢你,

1 个答案:

答案 0 :(得分:4)

您可以apply使用min

df['Min'] = df.Lists.apply(lambda x: min(x))
print (df)
       Lists  Min
0  [1, 2, 3]    1
1  [4, 5, 6]    4
2  [7, 8, 9]    7

感谢juanpa.arrivillaga的想法:

df['Min'] = [min(x) for x in df.Lists.tolist()]
print (df)
       Lists  Min
0  [1, 2, 3]    1
1  [4, 5, 6]    4
2  [7, 8, 9]    7

<强>计时

##[300000 rows x 2 columns]
df = pd.concat([df]*100000).reset_index(drop=True)

In [144]: %timeit df['Min1'] = [min(x) for x in df.Lists.values.tolist()]
10 loops, best of 3: 137 ms per loop

In [145]: %timeit df['Min2'] = [min(x) for x in df.Lists.tolist()]
10 loops, best of 3: 142 ms per loop

In [146]: %timeit df['Min3'] = [min(x) for x in df.Lists]
10 loops, best of 3: 139 ms per loop

In [147]: %timeit df['Min4'] = df.Lists.apply(lambda x: min(x))
10 loops, best of 3: 170 ms per loop