繁体   English   中英

如何在Pandas数据框中分配层次列名称

[英]how to assign hierarchical column names in pandas dataframe

我的CSV文件的前两行具有要用作列名的名称,前两列具有行名。 因此,该文件如下所示:

tp,desc,L,L,D,D
,,1,2,3,4
3001, foo, 23.1, 35.3, 52.0, 11.9
3010, bar, 31.l, 25.9, 13.9, 134.8

我能够将前两列设置为索引,但是被困在让前两行作为列名被接受

到目前为止,这是我的输入语句:

df = pd.read_csv("file.csv", index_col=[tp,desc])

谢谢。

尝试使用index_col指定“ index ”列,并解码您必须能够读取的数据。

from io import StringIO
import pandas as pd

data="tp,desc,L,L,D,D\n,,1,2,3,4\n3001, foo, 23.1, 35.3, 52.0, 11.9\n3010, bar, 31.l, 25.9, 13.9, 134.8"
df= pd.read_csv(StringIO(data.decode('UTF-8')),sep=',', index_col=[0,1])
print df

输出:

               L   L.1     D    D.1
tp   desc                          
NaN  NaN       1   2.0   3.0    4.0
3001  foo   23.1  35.3  52.0   11.9
3010  bar   31.l  25.9  13.9  134.8

尝试读取文件并以这种方式进行转换。 有不同的解决方案在这里 但这通常可以解决问题。

with open('example.csv', 'rb') as f:
    csv = f.read().decode("utf-8")

也许您可以尝试:

import pandas as pd

df = pd.read_csv('file.csv', header=None)

# getting names for columns and index:
cnames = zip(df.iloc[0,2:], df.iloc[1,2:])
inames = list(df.iloc[0,:2])    

#drop the rows with column names (for columns and index)
df.drop([0,1],axis=0,inplace=True)
#set the indexes
df.set_index([0,1],inplace=True)
# set the names for columns and indexes
df.columns = pd.MultiIndex.from_tuples(cnames)
df.index.names = inames

结果是:

               L             D        
               1      2      3       4
tp   desc                             
3001  foo   23.1   35.3   52.0    11.9
3010  bar   31.l   25.9   13.9   134.8

我使用了以下文件内容:

tp,desc,L,L,D,D
,,1,2,3,4
3001, foo, 23.1, 35.3, 52.0, 11.9
3010, bar, 31.l, 25.9, 13.9, 134.8

暂无
暂无

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

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