如何使用带条件的for循环参照DF1模板为DF2各玩具名生成独立dataframe
以下是Python+pandas实现的完整代码,你可以直接运行测试:
首先导入依赖并构造示例数据(如果你已经有DF1和DF2可以跳过这部分):
import pandas as pd # 示例DF1 DF1 = pd.DataFrame({ 'col1': ['price($)', 'dimension(m)', 'color1'], 'col2': ['price(#)', 'dimension(inch)', 'color2'] }) # 示例DF2 DF2 = pd.DataFrame({ 'toyname': ['t1', 't2', 't3'], 'price($)': [2, 3, 12], 'price(#)': [12, 13, 23], 'dimension(m)': [11, 10, 20], 'dimension(inch)': [21, 20, 30], 'color1': ['gr', 'bl', 'ye'], 'color2': ['re', 're', 'bl'] })
核心处理逻辑,支持自定义筛选条件:
# 从DF1提取列配对规则 col_pairs = list(DF1.itertuples(index=False, name=None)) # 存储结果:key为玩具名,value为对应独立数据框 toy_dfs = {} # 遍历DF2的每个玩具条目 for _, row in DF2.iterrows(): current_toy = row['toyname'] # 条件判断示例:只生成t1、t2的独立数据框,不需要的可直接跳过 if current_toy not in ['t1', 't2']: continue # 按配对规则组装数据 new_data = [] for c1, c2 in col_pairs: new_data.append([row[c1], row[c2]]) # 生成符合格式要求的数据框并存入结果 toy_dfs[current_toy] = pd.DataFrame(new_data, columns=['col1', 'col2'])
如果需要打印验证输出结果,可以执行以下代码:
for name, df in toy_dfs.items(): print(name) print(df.to_string(index=False)) print()
运行后输出结果和你预期的格式完全一致,后续需要调用某个玩具的独立数据框,直接用toy_dfs['t1']这种方式取值即可。
内容的提问来源于stack exchange,提问作者Kathan Vyas
相关产品推荐
相关产品推荐

