Pandas 将标签添加到一个df,然后将该df连接到另一个df-现在标签是一个列表-给出了什么?

Pandas 将标签添加到一个df,然后将该df连接到另一个df-现在标签是一个列表-给出了什么?,pandas,dataframe,concatenation,Pandas,Dataframe,Concatenation,我有两个csv文件需要连接。我把这两个csv文件读为dfs。一个有col标签,另一个没有。我将标签添加到需要它们的df中,然后连接两个df。连接很好,但是我添加的标签看起来像是单独的列表之类的。我不知道python在做什么,尤其是当你打印标签和df时,一切看起来都很好。把这种方法称为一种 当我读入csv时,我可以通过向csv添加col标签来解决这个问题。那么它工作得很好。把这种方法称为二。方法一发生了什么 代码和结果如下 方法一 #read in the vectors as a pandas

我有两个csv文件需要连接。我把这两个csv文件读为dfs。一个有col标签,另一个没有。我将标签添加到需要它们的df中,然后连接两个df。连接很好,但是我添加的标签看起来像是单独的列表之类的。我不知道python在做什么,尤其是当你打印标签和df时,一切看起来都很好。把这种方法称为一种

当我读入csv时,我可以通过向csv添加col标签来解决这个问题。那么它工作得很好。把这种方法称为二。方法一发生了什么

代码和结果如下

方法一

#read in the vectors as a pandas df vec
vecs=pd.read_csv(os.path.join(path,filename), header=None)

#label the feature vectors v1-vn and attach to the df
endrange=features+1
string='v'
vecnames=[string + str(i) for i in range(1,endrange)]
vecs.columns = [vecnames]
print('\nvecnames')
display(vecnames)  #they look ok here
display(vecs.head()) #they look ok here

#read in the IDs and phrases as a pandas df
recipes=pd.read_csv(os.path.join(path,'2a_2d_id_all_recipe_forms.csv'))
print('\nrecipes file - ids and recipe phrases')
display(recipes.head())

test=pd.concat([recipes, vecs], axis=1)
print('\ncol labels for vectors look like lists!')
display(test.head())
方法一的结果:

方法二

当我读取未标记的文件时,通过向csv添加col标签,它可以正常工作。为什么?

#label the feature vectors v1-vn and attach to the df
endrange=features+1
string='v'
vecnames=[string + str(i) for i in range(1,endrange)]

#read in the vectors as a pandas df and label the cols
vecs=pd.read_csv(os.path.join(path,filename), names=vecnames, header=None)

#read in the IDs and phrases as a pandas df
recipes=pd.read_csv(os.path.join(path,'2a_2d_id_all_recipe_forms.csv'))

test=pd.concat([recipes, vecs], axis=1)
print('\ncol labels for vectors as expected')
display(test.head())
方法二的结果


奇怪的行为来自这一行:

vecs.columns = [vecnames]
vecnames
已经是一个列表,但上面的一行将其包装在另一个列表中。列名在打印数据帧时正确显示,但将
vecs
与另一个数据帧连接会导致pandas将
vecs
的列名展开为单个元素元组

修复:将上述行更改为:

vecs.columns = vecnames

并按原样运行所有其他操作。

当代码依赖于与仅存在于系统上的文件交互时,很难诊断或再现这种行为。你能硬编码一些重现问题的示例数据帧吗?以图片形式发布代码或数据是不好的。无法将图片复制并粘贴到代码编辑器中。因此,要有人帮忙会困难得多,也就不太可能了。为了最大限度地利用网站,重要的是,包括创建一个示例。ok。接受批评。这真的很有趣,有助于深入了解python之美。我真的很感谢你抽出时间回答。
vecs.columns = vecnames