【问题标题】:First row to header with pandas熊猫头的第一行
【发布时间】:2020-07-09 06:52:01
【问题描述】:

我有以下熊猫数据框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 

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

del df.index.namethis post 都不是

df.columns.name = Nonethis postthis one 都不是(情况相同)

我怎样才能得到这个预期的输出:

           Objet Unités vendues 
1         Chaise              3 
2          Table              2 

【问题讨论】:

标签: python python-3.x pandas header


【解决方案1】:

首先在加载表格时如何定义它?

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

否则我猜你可以这样做:

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

【讨论】:

  • 当您在单独的文件或数组中拥有名称时,这并不容易。
【解决方案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])

【讨论】:

    【解决方案3】:

    使用skiprows 参数为我完成了这项工作:即skiprows=N 其中N = 要跳过的行数(在上面的示例中为 1),所以:

    df = pd.read_csv('filename', skiprows=1)
    

    【讨论】:

      猜你喜欢
      • 2023-03-13
      • 1970-01-01
      • 2017-12-12
      • 2019-08-01
      • 2013-12-02
      • 1970-01-01
      相关资源
      最近更新 更多