[英]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 将object
( list
)添加到单元格比较棘手
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.