根据某种条件将熊猫数据帧有效地分为两个数据帧

时间:2020-05-13 20:30:04

标签: python pandas dataframe

因此,我想基于特定列的if条件将给定的数据帧分为两个数据帧。 我目前正在通过遍历整个数据帧两次来实现这一点。请提出一些改进方法。

 player   score
 dan       10
 dmitri    45
 darren    15
 xae12     40

就像上面的数据框一样,我想将df分为两部分,以便一个df包含玩家得分小于15的行,另一个df包含其余行。我只想进行一次迭代。 (另外,如果答案可以是n dfs的通用答案,对我有很大帮助) 预先感谢。

3 个答案:

答案 0 :(得分:2)

IICU

使用布尔选择

m=df.score>15

Lessthan15=df[~m]
Morethan15=df[m]

Morethan15

enter image description here

LessThan15

enter image description here

答案 1 :(得分:2)

有两种方法可以根据您的要求选择数据框。我正在同一查询中进行时间分析,这样我们就可以知道哪个更快。

1)使用两次df

%%time

dataframe1  = dataframe[dataframe['score']>15]
dataframe2  = dataframe[dataframe['score']<=15]

输出来自Wall time: 4.06 ms

2)使用布尔和波浪号概念:

%%time

a = dataframe.score>15

dataframe1 = dataframe[a]
dataframe2 = dataframe[~a]

此查询在Wall time: 0.02 ms中给出输出

显然,第二种方法要快得多。

答案 2 :(得分:0)

尝试一下:

df_less_than_15 = df[df['score'] < 15]
df_more_than_15 = df[df['score'] >= 15]

您可以为每个给定的数据帧使用相同的内容。