如何用for循环逐个打印Pandas DataFrame中逗号分隔的列值
解决方法
你的原代码直接遍历df_merge.product_name的每个元素,得到的是带逗号的完整字符串,所以无法逐个打印拆分后的单个产品名。可以通过嵌套循环或者生成器表达式实现需求:
方法一:嵌套循环
先遍历每个带逗号的产品字符串,拆分后再遍历单个产品名打印:
import pandas as pd data = {'product_name': ['laptop,computer', 'printer,table', 'tablet,mobile', 'desk', 'chair,table'], 'price': [1200, 150, 300, 450, 200] } df_merge = pd.DataFrame(data) for product_str in df_merge.product_name: # 按逗号拆分字符串为单个产品的列表 single_products = product_str.split(',') # 逐个打印拆分后的产品名 for item in single_products: print(item)
方法二:生成器表达式(简洁版)
用生成器表达式一次性展开所有拆分后的元素,再遍历打印:
import pandas as pd data = {'product_name': ['laptop,computer', 'printer,table', 'tablet,mobile', 'desk', 'chair,table'], 'price': [1200, 150, 300, 450, 200] } df_merge = pd.DataFrame(data) # 生成器表达式展开所有单个产品名 for item in (product for s in df_merge.product_name for product in s.split(',')): print(item)
两种方法都会输出预期顺序的结果:
laptop computer printer table tablet mobile desk chair table
内容的提问来源于stack exchange,提问作者Jawed Sheikh
相关产品推荐
相关产品推荐

