染料+Pandas:返回条件伪变量序列

68bkxrlz  于 2023-01-19  发布在  其他
关注(0)|答案(3)|浏览(100)

在Pandas中,如果我想创建一列条件哑元(假设变量等于字符串时为1,不等于字符串时为0),那么我在Pandas中的后藤是:

data["ebt_dummy"] = np.where((data["paymenttypeid"]=='ebt'), 1, 0)

在dask Dataframe 中天真地尝试这个操作会抛出一个错误。按照文档中关于map_partitions的说明进行操作也会抛出一个错误:

data = data.map_partitions(lambda df: df.assign(ebt_dummy = np.where((df["paymenttypeid"]=='ebt'), 1, 0)),  meta={'paymenttypeid': 'str', 'ebt_dummy': 'i8'})

做这件事的好方法,或者最黑暗的方法是什么?

yk9xbfzb

yk9xbfzb1#

下面是一些示例数据:

In [1]:
df = pd.DataFrame(np.transpose([np.random.choice(['ebt','other'], (10)),
              np.random.rand(10)]), columns=['paymenttypeid','other'])

df

Out[1]:

  paymenttypeid                 other
0         other    0.3130770966143612
1         other    0.5167434068096931
2           ebt    0.7606898392115471
3           ebt    0.9424572692382547
4           ebt     0.624282017575857
5           ebt    0.8584841824784487
6         other    0.5017083765654611
7         other  0.025994123211164233
8           ebt   0.07045354449612984
9           ebt   0.11976351556850084

我们把它转换成 Dataframe

In [2]: data = dd.from_pandas(df, npartitions=2)

并使用apply(在系列上)指定:

In [3]:
data['ebt_dummy'] = data.paymenttypeid.apply(lambda x: 1 if x =='ebt' else 0, meta=('paymenttypeid', 'str'))
data.compute()

Out [3]:
  paymenttypeid                 other  ebt_dummy
0         other    0.3130770966143612          0
1         other    0.5167434068096931          0
2           ebt    0.7606898392115471          1
3           ebt    0.9424572692382547          1
4           ebt     0.624282017575857          1
5           ebt    0.8584841824784487          1
6         other    0.5017083765654611          0
7         other  0.025994123211164233          0
8           ebt   0.07045354449612984          1
9           ebt   0.11976351556850084          1
    • 更新日期:**

看起来您传递的meta是问题所在,因为这是有效的:

data = data.map_partitions(lambda df: df.assign(
                                    ebt_dummy = np.where((df["paymenttypeid"]=='ebt'), 1, 0)))

data.compute()

在我的例子中,如果我想指定meta,我必须传递当前data的数据类型,而不是我赋值后期望的数据类型:

data.map_partitions(lambda df: df.assign(
                                    ebt_dummy = np.where((df["paymenttypeid"]=='ebt'), 1, 0)), 
               meta={'paymenttypeid': 'str', 'other': 'float64'})
eit6fx6z

eit6fx6z2#

这对我也很有效:

data['ebt_dummy'] = dd.from_array(np.where((df["paymenttypeid"]=='ebt'), 1, 0))
8yparm6h

8yparm6h3#

我相信你要找的是一个三元运算。对于数字,像这样的东西应该可以工作。

import dask.dataframe as dd
import typing as t
def ternary(conditional: dd.Series, option_true: t.Union[float, int], option_false: t.Union[float, int]) -> dd.Series:
    return conditional * option_true + (~conditional) * option_false

data["ebt_dummy"] = ternary(data["paymenttypeid"]=='ebt', 1, 0)

相关问题