首页 > 解决方案 > 我想将列行字符串乘以 n 次

问题描述

输入

columnheader 
Test
Hello
World

输出

columnheader 
Test, Test 
Hello, Hello
World, World

df.iloc[:, [1]] = df.iloc[:, [1]].apply(lambda x : x ", " + x)

这可行,但我想使用 n 次重复而不是手动

标签: pythonpandas

解决方案


一个想法是join与列表中的重复值一起使用,以便在DataFrame.iloc没有嵌套[]的情况下使用第二列 select Series

N = 3
#selecting by position
df.iloc[:, 1] = df.iloc[:, 1].apply(lambda x: ', '.join([str(x)] * N))
#selecting by column name
df['columnheader'] = df['columnheader'].apply(lambda x: ', '.join([str(x)] * N))
print (df)
          columnheader
0     Test, Test, Test
1  Hello, Hello, Hello
2  World, World, World

或者添加分隔符,重复Series.mul,最后通过索引从右侧删除分隔符(最好避免strip- 如果在 column 结束,它也应该删除分隔符columnheader):

N = 3
sep = ', '
#selecting by position
df.iloc[:, 1] = df.iloc[:, 1].astype(str).add(sep).mul(N).str[:-len(sep)]
#selecting by column name
df['columnheader'] = df['columnheader'].astype(str).add(sep).mul(N).str[:-len(sep)]
print (df)
          columnheader
0     Test, Test, Test
1  Hello, Hello, Hello
2  World, World, World

推荐阅读