将DF列名称设置为索引(熊猫)

时间:2020-10-15 01:45:00

标签: python pandas plotly

我正在使用一个excel文件,该文件包含一堆基因名称以及它们在几年内每月出现的时间(如果有意义)。我目前使用熊猫读取文件并制作数据框。

输入:

import pandas as pd
import plotly.express as px

df = pd.read_csv('genes.csv', sep = ',', header = None)
print(df)

输出:

     0       1       2       3    ...     561      562      563      564
0    NaN  1971-1  1971-2  1971-3  ...  2017-9  2017-10  2017-11  2017-12
1  BRCA1       0       0       0  ...       0        0        0        0
2  BRCA2       0       0       0  ...       0        0        0        0
3   MAPK       0       0       0  ...       0        0        0        0

我知道要绘制该数据,并且一直在尝试弄清楚如何将日期设置为索引(不完全确定这是否是我需要做的)。我看到了一些有关使用set_index的信息,因此我尝试使用以下代码。这只是给我一个错误。

输入:

print(df.set_index([]).stack().reset_index(name='Date'))
fig = px.line(df, title = 'Human Gene Occurances Per Month')
fig.show()

输出:

ValueError: Must pass non-zero number of levels/codes

我正在尝试使用Plotly为每个基因创建一个图,这些图在x轴上绘制日期,在y轴上绘制计数。任何帮助是极大的赞赏。谢谢

也并非所有的计数都等于零,这就是打印时在压缩数据框中显示的正好数字。

2 个答案:

答案 0 :(得分:2)

import numpy as np 
import pandas as pd
import matplotlib.pyplot as p
#     0       1       2       3    ...     561      562      563      564
# 0    NaN  1971-1  1971-2  1971-3  ...  2017-9  2017-10  2017-11  2017-12
# 1  BRCA1       0       0       0  ...       0        0        0        0
# 2  BRCA2       0       0       0  ...       0        0        0        0
# 3   MAPK       0       0       0  ...       0        0        0        0

d={'0':['NaN','BRCA1','BRCA2'],'1':['1971-1',0,0],'2':['1971-2',1,0],'3':['1971-3',0,1]}
df =pd.DataFrame(data=d)
df=df.transpose()    # time series are typically in columns
df

enter image description here

#turn that column into actual dates, that pandas recognizes as such

df[0] = df[0].astype('datetime64[ns]')   
df

enter image description here

 # you probably mean the first row to be column headers

df.columns = df.iloc[0]             # set columns to first row
df.drop(df.index[0],inplace=True)   # drop that row

df

enter image description here

# set the first column to have the title "Date"

df.rename(columns={df.columns[0]: "Date"},inplace=True)
df

enter image description here

p.figure(figsize=(12,3),dpi=100)
p.plot(df.iloc[:,0],df.iloc[:,1], label= df.columns[1])
p.plot(df.iloc[:,0],df.iloc[:,2] ,label= df.columns[2])
p.legend()

enter image description here

熊猫比您坚持不懈地解决问题的方法更多。除非您每天工作8个小时,否则您会忘记的。我通过保持与个人Wiki中的示例完全兼容的方式来管理它,以便在忘记某些内容时可以更快地进行搜索。

答案 1 :(得分:2)

通常:

df.rename(columns=df.iloc[0], inplace = True)
df.drop(df.index[0], inplace=True)
df.set_index(<column name>, inplace=True)

在您的示例中;

# transpose dataframe first
df=df.T
df.rename(columns=df.iloc[0], inplace = True)
df.drop(df.index[0], inplace=True)
df.rename(columns={'nan':'Time'}, inplace=True)
df.set_index('Time', inplace=True)

您的数据框:

        BRCA1 BRCA2 MAPK
Time                    
1971-1      0     0    0
1971-2      0     0    0
1971-3      0     0    0
2017-9      0     0    0
2017-10     0     0    0
2017-11     0     0    0
2017-12     0     0    0

您的情节

这是使用最简单的方法完成的,将大熊猫的绘图支持设置为plotly。它看起来有点怪异的原因是您提供的数据集有限。我仅在其中添加了一些虚拟数据,以便可以辨别不同的轨迹。继续尝试您的真实数据,我敢肯定它会看起来很完美。

enter image description here

完整代码:

import pandas as pd
pd.options.plotting.backend = "plotly"

# data
df=pd.DataFrame({'0': {0: 'nan', 1: 'BRCA1', 2: 'BRCA2', 3: 'MAPK'},
                 '1': {0: '1971-1', 1: '0', 2: '0', 3: '0'},
                 '2': {0: '1971-2', 1: '0', 2: '0', 3: '0'},
                 '3': {0: '1971-3', 1: '1', 2: '0', 3: '0'},
                 '561': {0: '2017-9', 1: '1', 2: '2', 3: '0'},
                 '562': {0: '2017-10', 1: '1', 2: '2', 3: '0'},
                 '563': {0: '2017-11', 1: '1', 2: '2', 3: '3'},
                 '564': {0: '2017-12', 1: '1', 2: '2', 3: '3'}})

df=df.T
df.rename(columns=df.iloc[0], inplace = True)
df.drop(df.index[0], inplace=True)
df.rename(columns={'nan':'Time'}, inplace=True)
df.set_index('Time', inplace=True)
df.plot(template='plotly_dark')