如何删除 pandas 中的空列表?

How to remove empty list in pandas?

我正在从 csv 重编数据 我有一个这样的数据框:

product_title   variatons_color          
T-shirt          ['yellow','ornage'] 
T-shirt          []
T-shirt          ['blue','green']

我预期的数据框将如下所示

product_title   variatons_color          
T-shirt          ['yellow','ornage'] 
T-shirt         
T-shirt          ['blue','green']

我想删除空列表。如何在 pandas 中做到这一点?

更新1 我应用了 Scott Boston,YnjxsjmhBENY 解决方案。所有解决方案都为我的所有行填充 None 值,但我只需要为我的空列表填充 None 值。 当我 运行 type(df.loc[0,'variations_color']) 返回 str

使用布尔检查检查赋值

df.loc[~df['variatons_color'].astype(bool),'variatons_color'] = ''

更新

df.loc[df['variatons_color'].eq('[]'),'variatons_color'] = ''
import pandas as pd
df = pd.DataFrame({'product_title':['T-shirt']*3,
                   'variations_color':[['yellow', 'orange'],[],['blue', 'green']]})
df['variations_color'] = df['variations_color'].apply(lambda x: None if any(eval(str(x))) == False else x)
df

你可以试试

df['variatons_color'] = df['variatons_color'].apply(lambda lst: lst if len(lst) else '')
print(df)

  product_title   variatons_color
0       T-shirt  [yellow, ornage]
1       T-shirt
2       T-shirt     [blue, green]

只是 apply len:

df.loc[df['variations_color'].apply(len) == 0, 'variations_color'] = ''

df.loc[df['variations_color'].apply(len) == 0, 'variations_color'] =  np.nan

输出:

  product_title  variations_color
0       T-shirt  [yellow, orange]
1       T-shirt               NaN
2       T-shirt     [blue, green]

给定 df,

df = pd.DataFrame({'product_title':['T-shirt']*3,
                   'variations_color':[['yellow', 'orange'],[],['blue', 'green']]})

但是,如果你的数据名结构是这样的:

df = pd.DataFrame({'product_title':['T-shirt']*3,
                   'variations_color':['[yellow, orange]','[]','[blue, green]']})

然后,您可以使用以下方法:

df.loc[df['variations_color'] == '[]', 'variations_color'] = np.nan

输出:

  product_title  variations_color
0       T-shirt  [yellow, orange]
1       T-shirt               NaN
2       T-shirt     [blue, green]

注意第一个例子的区别

type(df.loc[0,'variations_color'])returns一个列表

并且,第二个 returns 海峡。 dataframe 的字符串表示形式是相同的,因此您无法在打印时仅通过查看它来判断。在 python 中,了解您正在使用的对象的类型(数据类型)始终很重要。

看这里!

import pandas as pd
from io import StringIO

data = '''
product_title   variatons_color          
T-shirt          ['yellow','ornage'] 
T-shirt          []
T-shirt          ['blue','green']
'''

df = pd.read_csv(StringIO(data), delim_whitespace=True)
df.variatons_color = df.variatons_color.apply(eval)
df
'''
  product_title   variatons_color
0       T-shirt  [yellow, ornage]
1       T-shirt                []
2       T-shirt     [blue, green]
'''



type(df.iat[0, 1])
# list


df.mask(df.applymap(len) == 0, None)
'''
  product_title   variatons_color
0       T-shirt  [yellow, ornage]
1       T-shirt              None
2       T-shirt     [blue, green]
'''

完成!