gpt4 book ai didi

python - 通过组合索引#、字符串创建列

转载 作者:太空宇宙 更新时间:2023-11-04 11:10:47 25 4
gpt4 key购买 nike

我有一个包含一列字符串的数据框。我想创建一个新列,在列表理解中将索引号和字符串列组合在一起。以下代码在循环中迭代执行此操作:

df=pd.DataFrame({'strings': ['string1','string2','string3']})
new_col=[]
for i in df['strings'].index.values:
new_col.append(str(i)+','+df['strings'][i])
df['new_col']=new_col

上面的代码可以工作但是很慢。我怎样才能在列表理解中做到这一点?

最佳答案

您可以将索引转换为字符串并像往常一样添加(数组)字符串:

df['new_col'] = df['strings'].index.astype(str) + ',' + df['strings']

输出:

   strings    new_col
0 string1 0,string1
1 string2 1,string2
2 string3 2,string3

关于python - 通过组合索引#、字符串创建列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58276088/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com