Skip to main content
 首页 » 编程设计

Python join之如何在循环中加入数据

2025年05月04日15mq0036

我怎样才能加入下面的数据,

# Convert Spark DataFrame to Pandas 
pandas_df = df.toPandas() 
print pandas_df 
 
   age     name 
0  NaN  Michael 
1   30     Andy 
2   19   Justin 

我目前的尝试,

persons = "" 
 
for index, row in pandas_df.iterrows(): 
    persons += str(row['name']) + ", " + str(row['age']) + "/ " 
    print row['name'], row['age'] 
 
print persons 

结果,

Michael, nan/ Andy, 30.0/ Justin, 19.0/  

但我在(末尾没有斜杠)之后,

Michael, nan/ Andy, 30.0/ Justin, 19.0 

请您参考如下方法:

如果你想保留循环遍历 each 的方法,那么你可以简单地删除最后一个 / ,方法是对其执行 rstrip() 从右侧剥离.示例 -

persons = "" 
 
for index, row in pandas_df.iterrows(): 
    persons += str(row['name']) + ", " + str(row['age']) + "/ " 
    print row['name'], row['age'] 
 
person = person.rstrip("/ ") 
print persons 

示例/演示 -

>>> person = "Michael, nan/ Andy, 30.0/ Justin, 19.0/ " 
>>> person = person.rstrip('/ ') 
>>> person 
'Michael, nan/ Andy, 30.0/ Justin, 19.0' 

但是如果你真的不想在循环中使用print row['name'], row['age'],那么你可以把它转换成一个生成器函数,然后让 str.join() 处理你想要的。示例 -

person = "/".join(",".join([str(row['name']), str(row['age'])]) for _, row in pandas_df.iterrows())