Python熊猫只有在匹配时才保持行
我有一个CSV加载到熊猫,看起来像这样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 |
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