根据我的研究,我发现我只能使用 apply
来格式化 Pandas 中的字符串,这在大型数据集中非常慢,因为 apply
本质上是一个循环整个数据。理论上,format
是一个可向量化的函数,因为它不依赖于其他行。因此,有什么方法可以对其进行向量化吗?
比如我的一个作品想做这个:
joined["timestamp"] = joined.apply(lambda row: args.date + " {:0>2d}:{:0>2d}:00".format(row["tid"]/6, row["tid"]%6*10), axis=1)
其中 tid
是一个整数。一些示例数据(加入
):(date="20170101"
)
tid timestamp
1 20170101 00:10:00
10 20170101 01:40:00
我认为通过格式化其他列来附加新的字符串列是一种常见的情况。
谢谢!
最佳答案
我相信你需要str.zfill
并将分区更改为楼层分区 (//
):
print (joined)
tid
0 1
1 10
a ='20170101'
b = ' ' + (joined["tid"] // 6).astype(str).str.zfill(2) + ':'
c = (joined["tid"] % 6 * 10).astype(str).str.zfill(2) + ':00'
joined["timestamp"] = a + b + c
print (joined)
tid timestamp
0 1 20170101 00:10:00
1 10 20170101 01:40:00
关于python - Pandas 中有矢量化的 string.format 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49554907/