Python 第一行到带有熊猫的标题
我有以下数据帧Python 第一行到带有熊猫的标题,python,python-3.x,pandas,header,Python,Python 3.x,Pandas,Header,我有以下数据帧df: 将熊猫作为pd导入 从io导入StringIO s='''\ “未命名:0”,“未命名:1” Objet,“小卖部” 躺椅,3 表2 塔博雷特,1 ''' df=pd.read_csv(字符串) 看起来是: Unnamed: 0 Unnamed: 1 0 Objet Unités vendues 1 Chaise 3 2 Table 2 3 Tabouret
df
:
将熊猫作为pd导入
从io导入StringIO
s='''\
“未命名:0”,“未命名:1”
Objet,“小卖部”
躺椅,3
表2
塔博雷特,1
'''
df=pd.read_csv(字符串)
看起来是:
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位于第一行)
我试图以多种方式删除它,但没有任何效果:
无论是del df.index.name还是from
来自或的df.columns.name=None
如何获得预期的输出:
Objet Unités vendues
1 Chaise 3
2 Table 2
当您首先加载表时,如何定义它
pd.read\u csv('filename',header=1)
否则我想你可以这么做:
df.drop('0',轴=1)
最简单的是
df = pd.read_csv('yourFile.csv', header=1)
否则
df.columns = [df.iloc[0]]
df.drop(index=0, inplace=True)
df.reset_index(inplace=True, drop=True)
把我的数据用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])
df=df.rename_axis(None)
这可能就是你想要的,当你把名字放在一个单独的文件或数组中时,这并不容易。
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])