简体   繁体   English

使用Apply时将列表分配给单个pandas数据框列

[英]Assign list to a single pandas dataframe column when using apply

I have a column in pandas dataframe in the format : "A,B,C,D" and I would like to split store it as a list instead [A,B,C,D]. 我在pandas数据框中有一个列,格式为:“ A,B,C,D”,我想将其拆分存储为列表,而不是[A,B,C,D]。 I am using the below code to do the conversion but I keep getting the following error : ValueError: Shape of passed values is (58110, 3), indices imply (58110, 36) 我正在使用以下代码进行转换,但始终出现以下错误: ValueError:传递的值的形状为(58110,3),索引暗示(58110,36)

def convert_list(df):    
  return  df['textlist'].split(',')


df['newcol']= df.apply(lambda x:convert_list(x),axis=1)

您需要str.split

df['newcol'] = df['textlist'].str.split(',')

Setup 设定

df = pd.DataFrame(dict(textlist=['a,b,c,d']))

df

  textlist
0  a,b,c,d

@jezrael's answer is perfect! @jezrael的答案是完美的! No need to do anything different. 无需做任何不同的事情。

df.assign(newcol=df.textlist.str.split(','))

However, your function (with one slight mod) would have worked like this: 但是,您的函数(带有一个小的mod)将像这样工作:

def convert_list(df):    
    return  df['textlist'].str.split(',')

df.assign(newcol=convert_list)

  textlist        newcol
0  a,b,c,d  [a, b, c, d]

And you could also use numpy's np.core.defchararray.split 您还可以使用numpy的np.core.defchararray.split

df.assign(newcol=np.core.defchararray.split(df.textlist.values.astype(str), ','))

  textlist        newcol
0  a,b,c,d  [a, b, c, d]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将函数应用于 Pandas Dataframe 的单列 - Apply function to single column of pandas Dataframe 使用pandas DataFrame.apply进行列操作 - Using pandas DataFrame.apply for column operations 将元组列表转换为 pandas dataframe 的单列? - convert list of tuples into single column of pandas dataframe? Pandas在数据帧的单个列上进行逻辑索引以分配值 - Pandas logical indexing on a single column of a dataframe to assign values 使用无需迭代即可将代码分配给pandas数据框 - assign codes to pandas dataframe using apply without iteration 如何将多个函数应用于单个pandas dataframe列? - How to apply several functions to a single pandas dataframe column? 如何在不使用多个 OR 的情况下将单个条件应用于数据框中的列列表并将值添加到第 4 列 - How to apply single condition to a list of columns in a dataframe and add value to 4th column without using multiple OR's Pandas:映射数据框列以列出并分配二进制值? - Pandas: map dataframe column to list and assign binary value? 如何将列表中的随机值分配给pandas数据框中的列? - How to assign random values from a list to a column in a pandas dataframe? 将 dataframe 中的每个字符串元素与一个列表进行比较,并将其分配给一个列 python pandas - Compare each string element in a dataframe to a list and assign it to a column, python pandas
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM