根据行创建数据框,哪些列满足某个条件PYTHON

时间:2016-05-19 19:20:30

标签: python pandas dataframe

我只需要使用某些行创建一个新数据框,特定列的值符合条件。

我有以下数据框(称为:result):

source  target weight
     0       0   0.00
     5       1   5.00
     6       2   7.00
     8       3   8.00
     1       4   0.00
     3       5   0.00
     6       6   4.00
     4       7   0.00

我需要得到这样的东西:

source  target weight
     5       1   5.00
     6       2   7.00
     8       3   8.00
     6       6   4.00

但是,我一直在使用以下程序,但是它们不起作用,我一遍又一遍得到相同的结果(第一个)。

result1 = result[result['weight'] > 0 ]

result1 = result.loc[result['weight'] > 0 ]

2 个答案:

答案 0 :(得分:1)

Credit @EdChum

大多数情况下,您的权重列为str,并且在该比较中,您的所有字符串均为> 0。将它们转为floatint或其他数字和问题解决。

Hightlight(执行此操作)

result1 = results[result['weight'].astype(float) > 0]

解释

设置1(问题)

text = """source  target weight
     0       0   0.00
     5       1   5.00
     6       2   7.00
     8       3   8.00
     1       4   0.00
     3       5   0.00
     6       6   4.00
     4       7   0.00"""

df = pd.read_csv(StringIO(text), delim_whitespace=1, dtype=str)
#                                                    ^^^^^^^^^
#                                               Create Problem

print df[df.weight > 0]

看起来像:

  source target weight
0      0      0   0.00
1      5      1   5.00
2      6      2   7.00
3      8      3   8.00
4      1      4   0.00
5      3      5   0.00
6      6      6   4.00
7      4      7   0.00

设置2(解决方案)

text = """source  target weight
     0       0   0.00
     5       1   5.00
     6       2   7.00
     8       3   8.00
     1       4   0.00
     3       5   0.00
     6       6   4.00
     4       7   0.00"""

df = pd.read_csv(StringIO(text), delim_whitespace=1, dtype=float)
#                                                    ^^^^^^^^^^^
#                                                    Fix Problem

print df[df.weight > 0]

看起来像:

   source  target  weight
1     5.0     1.0     5.0
2     6.0     2.0     7.0
3     8.0     3.0     8.0
6     6.0     6.0     4.0

根据您的具体情况,请执行以下操作:

result1 = results[result['weight'].astype(float) > 0]

答案 1 :(得分:0)

你刚刚删除零吗?如果是这样,你可以使用:

df.loc[~(df==0).all(axis=1)]
相关问题