如果Dask系列包含无法散列的类型,如何将其转换为字符串类型?

时间:2020-08-03 06:08:44

标签: python dask dask-dataframe

我想在任意一个Dask系列上调用.value_counts(),并且如果该系列包含不可散列的类型,我想将该系列转换为类型 string 。如果不需要,我不想将系列转换为字符串。我也不想在致电.compute()之前先致电.value_counts()。我尝试过

df = pd.DataFrame({"a":[[1], ["foo"], ["foo", "bar"]]})
df = dd.from_pandas(df, npartitions=1)
srs = df["a"]

try:
    val_counts = srs.value_counts()
except TypeError:
    srs = srs.astype(str)
    val_counts = srs.value_counts()

val_counts.compute()

出现错误

TypeError:不可散列的类型:“列表”

df = pd.DataFrame({"a":[[1], ["foo"], ["foo", "bar"]]})
df = dd.from_pandas(df, npartitions=1)
srs = df["a"]

def func(srs):
    try:
        val_counts = srs.value_counts()
    except TypeError:
        srs = srs.astype(str)
        val_counts = srs.value_counts()
    return val_counts

val_counts = dask.compute(func(srs))

给出相同的错误。

我也尝试过

df = pd.DataFrame({"a":[[1], ["foo"], ["foo", "bar"]]})
df = dd.from_pandas(df, npartitions=1)
srs = df["a"]

if srs.apply(lambda y: isinstance(y, list), meta=srs).any():
    srs = srs.astype(str)

srs.value_counts().compute()

出现错误

TypeError:尝试将dd.Scalar 转换为布尔值。

1 个答案:

答案 0 :(得分:2)

也许首先将列表转换成可哈希的东西(如元组)?

s.apply(tuple).value_counts()  ? 
相关问题