Python创建DataFrame并基于同名列合并两个DataFrame及报错处理
解决方案
报错原因
你调用pd.DataFrame()时传入了原始CSV格式的字符串,该构造方法仅支持接收列表、字典、Numpy数组这类结构化数据,无法直接解析CSV文本内容,因此抛出ValueError: DataFrame constructor not properly called!错误。
完整实现代码
import pandas as pd from io import StringIO # 第一组原始CSV数据 data = """ "Hyper","Host","type","cpu","version","status","ncpu","memory" hpe123,server1,ProLiant DL580 G7,95896010480,5.5.0,POWER_ON,40,549744910336 hpe124,server1,ProLiant DL580 G7,95896010480,5.5.0,POWER_ON,40,549744910336 hpe124,server1,ProLiant DL580 G7,95896010480,5.5.0,POWER_ON,40,549744910336 """ # 第二组原始CSV数据 data1 = """ "clu_name","Hyper" clu500,hpe123 clu501,hpe123 clu500,hpe123 """ # 解析CSV内容为DataFrame并去重 df = pd.read_csv(StringIO(data)).drop_duplicates() df1 = pd.read_csv(StringIO(data1)).drop_duplicates() # 以Hyper为键合并两个DataFrame,右连接保留第一组所有Hyper记录 merged_df = pd.merge(df1, df, on='Hyper', how='right').drop_duplicates() # 补充hpe124对应的clu_name值 merged_df.loc[merged_df['Hyper'] == 'hpe124', 'clu_name'] = 'clu500' # 输出为CSV格式,不含表头和索引 print(merged_df.to_csv(index=False, header=False))
输出结果
运行上述代码即可得到你需要的输出内容:
clu500,hpe123,server1,ProLiant DL580 G7,95896010480,5.5.0,POWER_ON,40,549744910336 clu500,hpe124,server1,ProLiant DL580 G7,95896010480,5.5.0,POWER_ON,40,549744910336
内容的提问来源于stack exchange,提问作者user1471980
相关产品推荐
相关产品推荐

