Pandas-根据行值有条件地为新列选择数据源列

2024-04-29 12:48:18 发布

您现在位置:Python中文网/ 问答频道 /正文

是否有允许根据条件从不同列中进行选择的pandas函数?这类似于SQL Select子句中的CASE语句。例如,假设我有以下数据帧:

foo = DataFrame(
    [['USA',1,2],
    ['Canada',3,4],
    ['Canada',5,6]], 
    columns = ('Country', 'x', 'y')
)

当Country='美国'时,我想从列'x'中选择,当Country='加拿大'时,我想从列'y'中选择,结果如下:

  Country  x  y  z
0     USA  1  2  1
1  Canada  3  4  4
2  Canada  5  6  6

[3 rows x 4 columns]

Tags: columns数据函数dataframepandassqlfoo语句
3条回答

这里有一个通用的解决方案,可以根据另一列中的值选择任意列。

这还有一个额外的好处,就是在一个简单的dict结构中分离查找逻辑,这使得修改变得容易。

import pandas as pd
df = pd.DataFrame(
    [['UK', 'burgers', 4, 5, 6],
    ['USA', 4, 7, 9, 'make'],
    ['Canada', 6, 4, 6, 'you'],
    ['France', 3, 6, 'fat', 8]],
    columns = ('Country', 'a', 'b', 'c', 'd')
)

我扩展到一个操作,其中条件结果存储在外部查找结构中(dict

lookup = {'Canada': 'd', 'France': 'c', 'UK': 'a', 'USA': 'd'}

为存储在dict中的每个列循环pd.DataFrame,并使用条件表中的值来确定要选择的列

for k,v in lookup.iteritems():
    filt = df['Country'] == k
    df.loc[filt, 'result'] = df.loc[filt, v] # modifies in place

给生活上一课

In [69]: df
Out[69]:
  Country        a  b    c     d   result
0      UK  burgers  4    5     6  burgers
1     USA        4  7    9  make     make
2  Canada        6  4    6   you      you
3  France        3  6  fat     8      fat

使用^{}other参数和^{}

>>> import pandas as pd
>>>
>>> foo = pd.DataFrame([
...     ['USA',1,2],
...     ['Canada',3,4],
...     ['Canada',5,6]
... ], columns=('Country', 'x', 'y'))
>>>
>>> z = foo['x'].where(foo['Country'] == 'USA', foo['y'])
>>> pd.concat([foo['Country'], z], axis=1)
  Country  x
0     USA  1
1  Canada  4
2  Canada  6

如果要将z作为列名,请指定keys

>>> pd.concat([foo['Country'], z], keys=['Country', 'z'], axis=1)
  Country  z
0     USA  1
1  Canada  4
2  Canada  6

这将起作用:

In [84]:

def func(x):
    if x['Country'] == 'USA':
        return x['x']
    if x['Country'] == 'Canada':
        return x['y']
    return NaN
foo['z'] = foo.apply(func(row), axis = 1)
foo
Out[84]:
  Country  x  y  z
0     USA  1  2  1
1  Canada  3  4  4
2  Canada  5  6  6

[3 rows x 4 columns]

您可以使用loc

In [137]:

foo.loc[foo['Country']=='Canada','z'] = foo['y']
foo.loc[foo['Country']=='USA','z'] = foo['x']
foo
Out[137]:
  Country  x  y  z
0     USA  1  2  1
1  Canada  3  4  4
2  Canada  5  6  6

[3 rows x 4 columns]

编辑

尽管使用loc的笨拙会随着更大的数据帧而更好地扩展,因为这里为每一行调用apply,同时使用布尔索引将被矢量化。

相关问题 更多 >