Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/355.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熊猫只有在匹配时才保持行_Python_Pandas - Fatal编程技术网

Python熊猫只有在匹配时才保持行

Python熊猫只有在匹配时才保持行,python,pandas,Python,Pandas,我有一个CSV加载到熊猫,看起来像这样 col1 | col2 | col3 | col4 -------------------------------- 1 | red | big | round 1 | blue | small | square 1 | pink | small | triangle 1 | puple | big | rectangle 1 | green | big |

我有一个CSV加载到熊猫,看起来像这样

col1  |  col2  |  col3  |  col4
--------------------------------
1     |  red   |  big   |  round
1     |  blue  |  small |  square
1     |  pink  |  small |  triangle
1     |  puple |  big   |  rectangle
1     |  green |  big   |  round
我只想保留col4为圆形或三角形的行。我知道我能做到

df[df.col4 == 'round']
但在这种情况下,我怎么也包括三角形呢


但是,我如何才能做相反的事情,并且仅在圆或拖尾时保持行?

另一个答案中提供了一个很好的例子:

针对您的具体情况:

你应该使用这个方法

例如,在您的案例中:

print(df[df.col4.isin(['round','triangle'])])
应为您提供以下输出:

   col1   col2   col3      col4
0     1    red    big     round
2     1   pink  small  triangle
4     1  green    big     round
如果您想要相反,您可以使用:

这将为您提供以下信息:

   col1   col2   col3       col4
1     1   blue  small     square
3     1  puple    big  rectangle

df.col4.isin(['round','triangle'])
。感谢这个示例和链接,如果我想将结果输出为单独的CSV而不是打印,这仍然是合适的方法吗?是的,绝对正确。看一看pandas.DataFrame.to_csv()方法,这样在您的例子中,它就可以像df[~df.col4.isin(['round','triangle'])一样简单。to_csv('output_file.csv'))
   col1   col2   col3       col4
1     1   blue  small     square
3     1  puple    big  rectangle