Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.7 熊猫根据重复值的列值保留行_Python 2.7_Pandas - Fatal编程技术网

Python 2.7 熊猫根据重复值的列值保留行

Python 2.7 熊猫根据重复值的列值保留行,python-2.7,pandas,Python 2.7,Pandas,我有一个熊猫数据框和一个值列表。我希望保留原始DF中具有属于我的值列表的特定列值的所有行。但是,要从中选择行的列表具有重复的值。每次我再次遇到相同的值时,我都希望将具有该列值的行再次添加到我的新数据框中 假设我的框架名称是:with_prot_choice_df,我的列表是:with_prot_choices 如果我发出以下命令: with_prot_choice_df = with_df[with_df[0].isin(with_prot_choices)] 然后,这将只保留一次行(就好像列

我有一个熊猫数据框和一个值列表。我希望保留原始DF中具有属于我的值列表的特定列值的所有行。但是,要从中选择行的列表具有重复的值。每次我再次遇到相同的值时,我都希望将具有该列值的行再次添加到我的新数据框中

假设我的框架名称是:with_prot_choice_df,我的列表是:with_prot_choices

如果我发出以下命令:

with_prot_choice_df = with_df[with_df[0].isin(with_prot_choices)]
然后,这将只保留一次行(就好像列表中只有唯一的值一样)

我不想对for循环执行此操作,因为我将重复此过程很多次,这将非常耗时。 如有任何建议,将不胜感激。谢谢

我在这里添加了一个示例:

假设我的数据帧是:

col1   col2
a      1
a      6
b      2
c      3
d      4  
我的清单是: lst=[a,b,a,a]

我希望我的新数据帧,新的_df是: 新德里

col1   col2
a      1
a      6
b      2
a      1
a      6
a      1
a      6  

似乎您需要
reindex

df.set_index('col1').reindex(lst).reset_index()
Out[224]: 
  col1  col2
0    a     1
1    b     2
2    a     1
3    a     1
更新

df.merge(pd.DataFrame({'col1':lst}).reset_index()).sort_values('index').drop('index',1)
Out[236]: 
  col1  col2
0    a     1
3    a     6
6    b     2
1    a     1
4    a     6
2    a     1
5    a     6

ValueError:无法从重复的Axis重新编制索引我认为出现此错误是因为我的数据框重复了第一列的值。在这里,我在我最初的postbeatiful中添加了这个示例,它在数千行上运行不到一秒钟。谢天谢地,我永远也不会明白这一点。@user3289556yw~:-)快乐的编码