简体   繁体   English

Pandas DataFrame仅命名1列

[英]Pandas DataFrame naming only 1 column

Is there a way with Pandas Dataframe to name only the first or first and second column even if there's 4 columns : 有没有办法让Pandas Dataframe只命名第一列或第一列和第二列,即使有4列:

Here 这里

for x in range(1, len(table2_query) + 1):
    if x == 1:
        cursor.execute(table2_query[x])
        df = pd.DataFrame(data=cursor.fetchall(), columns=['Q', col_name[x-1]])

and it gives me this : 它给了我这个:

AssertionError: 2 columns passed, passed data had 4 columns AssertionError:传递了2列,传递的数据有4列

Consider the df : 考虑一下df

df = pd.DataFrame(np.arange(8).reshape(2, 4), columns=list('ABCD'))
df

在此输入图像描述

then use rename and pass a dictionary with the name changes to the argument columns : 然后使用rename并将名称更改的字典传递给参数columns

df.rename(columns=dict(A='a', B='b'))

在此输入图像描述

Instantiating a DataFrame while only naming a subset of the columns 仅在命名列的子集时实例化DataFrame

When constructing a dataframe with pd.DataFrame , you either don't pass an index/columns argument and let pandas auto-generate the index/columns object, or you pass one in yourself. 使用pd.DataFrame构造数据pd.DataFrame ,要么不传递索引/列参数,要么让pandas自动生成索引/列对象,要么自己传递一个。 If you pass it in yourself, it must match the dimensions of your data. 如果您自己传递,则必须与数据的尺寸相匹配。 The trouble of mimicking the auto-generation of pandas while augmenting just the ones you want is not worth the trouble and is ugly and is probably non-performant. 模仿大熊猫的自动生成同时增加你想要的大熊猫的麻烦并不值得麻烦,而且很丑陋并且可能是非高效的。 In other words, I can't even think of a good reason to do it. 换句话说,我甚至没有想到这样做的充分理由。

On the other hand, it is super easy to rename the columns/index values. 另一方面,重命名列/索引值非常容易。 In fact, we can rename just a few. 事实上,我们可以重命名一些。 I think below is more in line with the spirit of your question: 我认为下面更符合你的问题的精神:

df = pd.DataFrame(np.arange(8).reshape(2, 4)).rename(columns=str).rename(columns={'1': 'A', '3': 'F'})
df

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM