2016-08-04 51 views
1

我想通過基於特定列中的值選擇行來限制打印的行。熊貓 - 基於一列中的值打印有限的行

例如:

Column1, Column2, Column3 
aaa, bbb, ccc 
none, ddd, ggg 

我只是想打印的行,其中Column1價值none

這是我的代碼:

for v in df: 
    if 'none' in df['2nd_prize']: 
     print v 
+2

請顯示您的嘗試。 – merlin2011

+0

for df ['2nd_prize']: if'none'in df ['2nd_prize']: print v – Fawad

+0

我建議您將示例輸入的完整示例放入問題中,而不是在註釋中添加行。 – merlin2011

回答

1
for row in table: 
    if row[0] is none: 
    print row 
1

你可以使用loc來限制包含在Column 1"none"行子集的數據幀的行,如下所示:

數據準備

In [1]: import pandas as pd 
    ...: from io import StringIO 
    ...: 

In [2]: df = pd.read_csv(StringIO(
    ...: ''' 
    ...: Column1, Column2, Column3 
    ...: aaa, bbb, ccc 
    ...: none, ddd, ggg 
    ...: kkk, jjj, ppp 
    ...: none, eee, fff 
    ...: ''')) 

操作

In [3]: df.loc[df['Column1'] == "none"] 
Out[3]: 
    Column1 Column2 Column3 
1 none  ddd  ggg 
3 none  eee  fff 
+1

非常感謝。有用。 – Fawad

1

您可以使用boolean indexing用面膜:

import pandas as pd 

df = pd.DataFrame({'Column2': {0: 'bbb', 1: 'ddd'}, 
        'Column1': {0: 'aaa', 1: 'none'}, 
        'Column3': {0: 'ccc', 1: 'ggg'}}) 

print (df) 
    Column1 Column2 Column3 
0  aaa  bbb  ccc 
1 none  ddd  ggg 

print (df['Column1'] == "none") 
0 False 
1  True 
Name: Column1, dtype: bool 

print (df[df['Column1'] == "none"]) 
    Column1 Column2 Column3 
1 none  ddd  ggg 

如果值包含字符串開頭空格,使用str.strip

import pandas as pd 

df = pd.DataFrame({'Column2': {0: ' bbb', 1: ' ddd'}, 
        'Column1': {0: ' aaa', 1: ' none'}, 
        'Column3': {0: ' ccc', 1: ' ggg'}}) 

print (df) 
    Column1 Column2 Column3 
0  aaa  bbb  ccc 
1 none  ddd  ggg 

print (df['Column1'].str.strip() == "none") 
0 False 
1  True 
Name: Column1, dtype: bool 

print (df[df['Column1'].str.strip() == "none"]) 
    Column1 Column2 Column3 
1 none  ddd  ggg 
1

這是一個額外的方法它首先手動刪除空白,然後提供處理後的文件內容熊貓。

import pandas as pd 
from io import StringIO 

# First strip out the whitespace 
contents = open('Input.txt').read().splitlines() 
contents = "\n".join([",".join([x.strip() for x in y.split(",")]) for y in contents]) 

# Convert to a stringIO to feed to pandas 
df = pd.read_csv(StringIO(unicode(contents, 'utf-8'))) 

print df[df['Column1'] == "none"] 
+0

謝謝@ merlin2011 – Fawad