简体   繁体   English

新列,每个元素作为列表熊猫

[英]new column with each element as a list pandas

I have some data frames where I want to add new columns, and in this new column each element should be a string for example of two rows, 我有一些数据框要在其中添加新列,在这个新列中,每个元素应该是一个字符串,例如两行,

df
           index colA colB 
           0     a    a1
           1     b    b1

Now I can add new column as 现在我可以添加新列为

df['colC']=5
           index colA colB colC
           0     a    a1   5
           1     b    b1   5

now I want to add a third column with each element as list 现在我想添加第三列,每个元素作为列表

           index colA colB colC
           0     a    a1   ['m','n','p']
           1     b    b1   ['m','n','p']

but, 但,

df['colC']=['m','n','p'] is giving error
ValueError: Length of values does not match length of index

which is obvious. 这是显而易见的。

I know in our example I can do

df['colC']=[['m','n','p'],['m','n','p']]

But I want to set each element to same list of strings, when I do not know number of rows. 但是当我不知道行数时,我想将每个元素设置为相同的字符串列表。 Can anyone suggest something easy to achieve this. 任何人都可以提出一些容易实现的建议。

Adding object ( list ) to cell is tricky objectlist )添加到单元格比较棘手

df['colC']=[['m','n','p']]*len(df)

Or 要么

df['colC'] = [list('mnp') for _ in range(len(df))]

df returns: df返回:

   index colA colB       colC
0      0    a   a1  [m, n, p]
1      1    b   b1  [m, n, p]

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

相关问题 列表中每个元素的新列 - New column for each element in a list 为 pandas dataframe 中的列中的每个值计算列表中每个元素的 perc - Calculate perc of each element in a list for each value in column in pandas dataframe Pandas 列表列,append 每个列表的新列 - Pandas column of lists, append a new column to each list 如何将每个嵌套字典的元素转换为新的 pandas 列? - How to convert each nested dictionary' element to a new pandas column? 将每个列列表元素转换为 pandas dataframe 中的 JSON - converting each column list element to JSON in a pandas dataframe Pandas 列表列,为每个列表元素创建一行 - Pandas column of lists, create a row for each list element 熊猫为字典值中列表的每个元素创建一列? - Pandas create a column for each element of a list in a dictionary value? 将 dataframe 中的每个字符串元素与一个列表进行比较,并将其分配给一个列 python pandas - Compare each string element in a dataframe to a list and assign it to a column, python pandas 将列表中的每个元素映射到pandas数据框中的不同列 - Mapping each element in list to different column in pandas dataframe pandas:计算列表中每个元素在列表列中唯一出现的次数 - pandas: count the number of unique occurrences of each element of list in a column of lists
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM