2024-04-19 13:02:21 发布
网友
我有一个熊猫数据框。其中一列是列表列表。你知道吗
执行以下操作的最佳方法是什么:
IIUC公司
df.A=[x if x else ['other'] for x in df.A ] df Out[298]: A 0 [other] 1 [steel] 2 [steel] 3 [other] 4 [tarmac] 5 [other]
有很多原因不应该在对象中使用列表。您的第一个调用端口应该是提取字符串并将序列转换为分类数据:
df = pd.DataFrame({'A': [[], ['steel'], ['steel'], [], ['tarmac'], []]}) df['A'] = df['A'].str[0].fillna('other').astype('category') print(df) A 0 other 1 steel 2 steel 3 other 4 tarmac 5 other
如果坚持通过Python级别的循环使用低效且不可矢量化的操作,那么可以通过以下方式实现您想要的:
df['A'] = df['A'].str[0].fillna('other').apply(lambda x: [x]) print(df) A 0 [other] 1 [steel] 2 [steel] 3 [other] 4 [tarmac] 5 [other]
此时,分类数据不是一个选项,因为分类不支持一系列列表,因为list是不可散列的。你知道吗
list
另一个窍门:
>>> df A 0 [] 1 [steel] 2 [steel] 3 [] 4 [tarmac] 5 [] >>> df.A.apply(lambda y: "[other]" if len(y)==0 else y) 0 [other] 1 [steel] 2 [steel] 3 [other] 4 [tarmac] 5 [other] Name: A, dtype: object
或:
>>> df['A'].apply(lambda x: x if x else ['other']) 0 [other] 1 [steel] 2 [steel] 3 [other] 4 [tarmac] 5 [other] Name: A, dtype: object
IIUC公司
有很多原因不应该在对象中使用列表。您的第一个调用端口应该是提取字符串并将序列转换为分类数据:
如果坚持通过Python级别的循环使用低效且不可矢量化的操作,那么可以通过以下方式实现您想要的:
此时,分类数据不是一个选项,因为分类不支持一系列列表,因为
list
是不可散列的。你知道吗另一个窍门:
或:
相关问题 更多 >
编程相关推荐