gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:05:29 26 4
gpt4 key购买 nike

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

# 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())

关于Python join - 如何在循环中加入数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32043042/

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