第一行到带有Pandas的标题

2024-10-03 15:31:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据帧df

import pandas as pd
from io import StringIO
s = '''\
"Unnamed: 0","Unnamed: 1"   
Objet,"Unités vendues"  
Chaise,3
Table,2
Tabouret,1
'''
df = pd.read_csv(StringIO(s))

看起来是:

  Unnamed: 0     Unnamed: 1
0      Objet  Unités vendues
1     Chaise                 3
2      Table                 2
3   Tabouret                 1

我的目标是将第一行作为标题

我使用:

headers = df.iloc[0]
df.columns = [headers]  

但是,“0”出现在索引列名中(这是正常的,因为0位于第一行)

0          Objet Unités vendues 
1         Chaise              3 
2          Table              2 

我试图以多种方式删除它,但没有任何效果:

this postdel df.index.name都不是

无论是从{a2}还是从{a3}来的{}(情况相同)

如何获得预期的输出:

           Objet Unités vendues 
1         Chaise              3 
2          Table              2 

Tags: 数据importpandasdfastableunitheaders
2条回答

把我的数据用U表示,把我的列名用Un表示,我想出了这个算法。 如果你能缩短它,请这样做

U = pd.read_csv('U.csv', header = None) #.to_numpy()
Un = pd.read_csv('namesU.csv', header=None).T # Read your names csv, in my case they are in one column
Un = Un.append(U) # append the data U to the names
Un.reset_index(inplace=True, drop=True) # reset the index and drop the old one, so you don't have duplicated indices
Un.columns = [Un.iloc[0]] # take the names from the first row
Un.drop(index=0, inplace=True) # drop the first row
Un.reset_index(inplace=True, drop=True) # Return the index counter to start from 0

另一种选择:

Un = pd.read_csv('namesY.csv', header=None) # Read your names csv, in my case they are in one column
Un = list( Un[0] ) 
Un = pd.DataFrame(U, columns=[Un])

当您首先加载表时,如何定义它

pd.read_csv('filename', header = 1)

否则我想你可以这么做:

df.drop('0', axis = 1)

相关问题 更多 >