Требуется код pandas, который преобразует df с несколькими выборками для запуска блочной диаграммы - PullRequest
0 голосов
/ 08 мая 2020

Я пишу сценарий для создания коробчатых диаграмм из некоторых данных RNA-Seq.

Псевдокод

1. Select a row based on gene name 
2. make a column for each type of cell 
3. make box plot 

У меня 1 и 3 вниз

df2 = df[df[0].str.match("TCAP")]
????
import plotly.express as px
fig = px.box(df,x="CellType",y = "Expression",title = "GENE")
fig.show()

Код должен преобразовать следующие таблицы

Gene    Celltype-1_#1  Celltype-1_#2  Celltype-1_#3  Celltype-2_#1  Celltype-2_#2  Celltype-2_#3

A          1                1              1              3              3            3
B          5                5              5              4              4            4

к этому Используя: df2 = df [df [0] .str.match ("TCAP")]

 Gene    Celltype-1_#1  Celltype-1_#2  Celltype-1_#3  Celltype-2_#1  Celltype-2_#2  Celltype-2_#3

    A          1                1              1              3              3            3

Затем мне нужен код, чтобы сделать это в этом

Gene  CellType   Expression    

 A       1           1

 A       1           1

 A       1           1

 A       2           3

 A       2           3

 A       2           3    

1 Ответ

2 голосов
/ 08 мая 2020

Вы можете использовать метод DataFrame.stack для такого рода преобразования.

# need to have an index to make stack work
df = df.set_index('Gene')

# stack returns a series here
df = df.stack().to_frame().reset_index()

# At this point we have:
#     Gene        level_1  0
#  0     A  Celltype-1_#1  1
#  1     A  Celltype-1_#2  1
#  2     A  Celltype-1_#3  1
#  3     A  Celltype-2_#1  3
#  4     A  Celltype-2_#2  3
#  5     A  Celltype-2_#3  3
#  6     B  Celltype-1_#1  5
#  7     B  Celltype-1_#2  5
#  8     B  Celltype-1_#3  5
#  9     B  Celltype-2_#1  4
#  10    B  Celltype-2_#2  4
#  11    B  Celltype-2_#3  4

df.columns = ['Gene', 'Celltype', 'Expression']

# optionally rename values in celltype column
df['Celltype'] = df['Celltype'].apply(lambda t: t[9:10])

# now you can select by Gene or any other columns and pass to Plotly:
print(df[df['Gene'] == 'A'])

#     Gene Celltype  Expression
#  0     A        1           1
#  1     A        1           1
#  2     A        1           1
#  3     A        2           3
#  4     A        2           3
#  5     A        2           3

Обратите внимание, что, предварительно сложив весь фрейм данных, теперь просто выбрать несколько генов одновременно и вместе передайте их в Plotly:

df_many = df[df['Gene'].isin(['A', 'B'])]
...