python - 我想将列行字符串乘以 n 次
问题描述
输入
columnheader
Test
Hello
World
输出
columnheader
Test, Test
Hello, Hello
World, World
df.iloc[:, [1]] = df.iloc[:, [1]].apply(lambda x : x ", " + x)
这可行,但我想使用 n 次重复而不是手动
解决方案
一个想法是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
推荐阅读
- java - [42000][1044] 用户 'bryce901'@'%' 拒绝访问 Intellij 上的数据库 'information_schema'
- c++ - 关于搬出容器的标准保证
- c# - 如果在编译时知道,有条件地实现 c# 接口?
- groovy - Groovy 代码 - 从列表中获取第 n 个值
- lisp - Racket 中 C 浮点数的正确指针类型转换是什么?
- php - MongoDB PHP 驱动程序无法在 Ubuntu AWS 上运行
- angular - 如何修复从 Angular 7 到 Jersey 服务的 http 调用中的会话丢失
- swift - 核心数据:保存对象时“调用”扩展中的计算属性
- android - Android studio kotlin 画线功能
- javascript - 如何删除选定的列表元素,而不是仅删除顶部 li 标记