Python 使用元素作为列表对数据帧进行切片
我的dataframe将列表作为元素,我希望有更有效的方法来检查某些条件。 我的数据框看起来像这样Python 使用元素作为列表对数据帧进行切片,python,pandas,Python,Pandas,我的dataframe将列表作为元素,我希望有更有效的方法来检查某些条件。 我的数据框看起来像这样 col_a col_b 0 100 [1, 2, 3] 1 200 [2, 1] 2 300 [3] 我只想得到列b中有1的行。 我试过天真的方法 临时列表=列表() 对于这样的大数据帧,这需要很多时间。如何使搜索更有效地搜索这样的数据帧?您可以通过列表理解来检查给定列表中是否存在1,并使用结果在数据帧上执行: df.loc[[1 in i for i in df.col_B ]
col_a col_b
0 100 [1, 2, 3]
1 200 [2, 1]
2 300 [3]
我只想得到列b中有1的行。
我试过天真的方法
临时列表=列表()
对于这样的大数据帧,这需要很多时间。如何使搜索更有效地搜索这样的数据帧?您可以通过列表理解来检查给定列表中是否存在
1
,并使用结果在数据帧上执行:
df.loc[[1 in i for i in df.col_B ],:]
col_a col_B
0 100 [1, 2, 3]
1 200 [2, 1]
下面是使用
集合的另一种方法:
df[df.col_B.ne(df.col_B.map(set).sub({1}).map(list))]
col_a col_B
0 100 [1, 2, 3]
1 200 [2, 1]
与列表理解和loc一起使用,用于seelct列列a
:
a = df1.loc[[1 in x for x in df1['col_b']], 'col_a'].tolist()
print (a)
[100, 200]
如果需要,请选择第一列:
a = df1.iloc[[1 in x for x in df1['col_b']], 0].tolist()
print (a)
[100, 200]
如果需要所有行:
df2 = df1[[1 in x for x in df1['col_b']]]
print (df2)
col_a col_b
0 100 [1, 2, 3]
1 200 [2, 1]
另一种带有set
s和isdisjoint
的解决方案:
df2 = df1[~df1['col_b'].map(set({1}).isdisjoint)]
print (df2)
col_a col_b
0 100 [1, 2, 3]
1 200 [2, 1]
结果:
col_a col_b
0 100 [1, 2, 3]
1 200 [2, 1]
我尝试了这种方法:
df['col_b'] = df.apply(lambda x: eval(x['col_b']), axis = 1)
s=df['col_b']
d = pd.get_dummies(s.apply(pd.Series).stack()).sum(level=0)
df = pd.concat([df, d], axis=1);
print(df)
print('...')
print(df[1.0])
这给了我末尾类似的索引(名称为1.0
的列作为数字):
要打印结果,请执行以下操作:
df.loc[df[1.0]==1, ['id', 'col_a', 'col_b']]
伟大的解决方案!
df['col_b'] = df.apply(lambda x: eval(x['col_b']), axis = 1)
s=df['col_b']
d = pd.get_dummies(s.apply(pd.Series).stack()).sum(level=0)
df = pd.concat([df, d], axis=1);
print(df)
print('...')
print(df[1.0])
id col_a col_b 1.0 2.0 3.0
0 1 100 (1, 2, 3) 1 1 1
1 2 200 (1, 2) 1 1 0
2 3 300 3 0 0 1
...
0 1
1 1
2 0
Name: 1.0, dtype: uint8
df.loc[df[1.0]==1, ['id', 'col_a', 'col_b']]