栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用pandas比较两列

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用pandas比较两列

您可以使用np.where。如果

cond
是布尔数组,
A
并且
B
是数组,则

C = np.where(cond, A, B)

将C定义为等于

A
哪里
cond
为True,
B
哪里
cond
为False。

import numpy as npimport pandas as pda = [['10', '1.2', '4.2'], ['15', '70', '0.03'], ['8', '5', '0']]df = pd.Dataframe(a, columns=['one', 'two', 'three'])df['que'] = np.where((df['one'] >= df['two']) & (df['one'] <= df['three'])          , df['one'], np.nan)

产量

  one  two three  que0  10  1.2   4.2   101  15   70  0.03  NaN2   8    5     0  NaN

如果您有多个条件,则可以使用np.select代替。例如,如果你想

df['que']
等于
df['two']
df['one']< df['two']
,则

conditions = [    (df['one'] >= df['two']) & (df['one'] <= df['three']),     df['one'] < df['two']]choices = [df['one'], df['two']]df['que'] = np.select(conditions, choices, default=np.nan)

产量

  one  two three  que0  10  1.2   4.2   101  15   70  0.03   702   8    5     0  NaN

如果我们可以假设

df['one'] >= df['two']
when
df['one'] < df['two']
为False,那么条件和选择可以简化为

conditions = [    df['one'] < df['two'],    df['one'] <= df['three']]choices = [df['two'], df['one']]

(如果包含

df['one']
df['two']
包含NaN,则该假设可能不正确。)


注意

a = [['10', '1.2', '4.2'], ['15', '70', '0.03'], ['8', '5', '0']]df = pd.Dataframe(a, columns=['one', 'two', 'three'])

用字符串值定义一个Dataframe。由于它们看起来是数字,因此最好将这些字符串转换为浮点数:

df2 = df.astype(float)

但是,这会改变结果,因为字符串会逐个字符地进行比较,而浮点数会进行数字比较。

In [61]: '10' <= '4.2'Out[61]: TrueIn [62]: 10 <= 4.2Out[62]: False


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/659579.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号