如何修复TypeError:字符串索引必须是整数

2024-09-29 18:42:26 发布

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

我正在从pyspark中的mapInPandas函数传递数据帧。所以我需要ID列的所有值都应该用逗号(,)分隔,就像这样'H57R6HU87','A1924334','496A4806'

x1['ID']看起来像这样

H57R6HU87
A1924334
496A4806'

这是我获得唯一ID的代码,我得到的是类型错误:字符串索引必须是整数

# batch_iter= cust.toPandas()
  
for x1 in batch_iter:
   IDs= ','.join(f"'{i}'" for i in x1['ID'].unique())


Tags: 函数代码inid类型forbatchpyspark
1条回答
网友
1楼 · 发布于 2024-09-29 18:42:26

您可能不需要循环,请尝试:

batch_iter = cust.toPandas()
IDs = ','.join(f"'{i}'" for i in batch_iter['ID'].unique())

或者,您可以尝试仅使用Spark功能:

df2 = df.select(F.concat_ws(',', F.collect_set('ID')).alias('ID'))

如果要使用mapInPandas,请执行以下操作:

def pandas_func(iter):
    for x1 in iter:
        IDs = ','.join(f"'{i}'" for i in x1['ID'].unique())
        yield pd.DataFrame({'ID': IDs}, index=[0])

df.mapInPandas(pandas_func)
# But I suspect you want to do this instead:
# df.repartition(1).mapInPandas(pandas_func)

相关问题 更多 >

    热门问题