【问题标题】:apply lstrip on every element in dataframe of lists对列表数据框中的每个元素应用 lstrip
【发布时间】:2019-06-12 08:47:17
【问题描述】:

在我的数据框中,每个单元格都是一个带有字符串的列表。问题是每个字符串前面都包含一个空格

a={'names':[[' Peter',' Alex'],[' Josh',' Hans']]}
df=pd.DataFrame(a)

我想删除空格。 对于我会使用的单个列表

y=[]
x = [' ab',' de',' cd']
for i in x:
    d=i.strip()
    y.append(d)
print (y)
['ab', 'de', 'cd']

所以我尝试为数据框构造类似的东西

 stripped=[]
    df=pd.DataFrame(a)
    for index,row in df.iterrows():
        d=df.names.apply(lambda x: x.lstrip()) 
        stripped.append(d)
    print(stripped)

返回

'list' 对象没有属性 'lstrip'

如果我打电话给

for index,row in df.iterrows():
    d=df.names.str.lstrip()
    stripped.append(d)
print(stripped)

它返回 Nan 列表

【问题讨论】:

    标签: python pandas list strip


    【解决方案1】:

    这应该可以工作

    df['names'] = df['names'].apply(lambda x: [i.strip() for i in x])
    

    输出

               names
    0  [Peter, Alex]
    1   [Josh, Hans]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-09
      • 2020-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-21
      相关资源
      最近更新 更多