Python pandasによると、列は見つかりませんが、csvファイル内に存在します

アルヴィン・クルヴィラ

だから私はこのスクリプトを持っています

mport pandas as pd
import numpy as np
PRIMARY_TUMOR_PATIENT_ID_REGEX = '^.{4}-.{2}-.{4}-01.*'
SHORTEN_PATIENT_REGEX = '^(.{4}-.{2}-.{4}).*'

def mutations_for_gene(df):
  mutated_patients = df['identifier'].unique()
  return pd.DataFrame({'mutated': np.ones(len(mutated_patients))}, index=mutated_patients)
  
def prep_data(mutation_path):
  df = pd.read_csv(mutation_path, low_memory=True, dtype=str, header = 0)#Line 24 reads in a line memory csv file from the given path and parses it based on '\t' delimators, and casts the data to str
  
  df = df[~df['Hugo_Symbol'].str.contains('Hugo_Symbol')] #analyzes the 'Hugo_Symbol' heading within the data and makes a new dataframe where any row that contains 'Hugo_Symbol' is dropped

  df['Hugo_Symbol'] = '\'' + df['Hugo_Symbol'].astype(str) # Appends ''\'' to all the data remaining in that column
  
  df['Tumor_Sample_Barcode'] = df['Tumor_Sample_Barcode'].str.strip() #strips away whitespace from the data within this heading
  non_silent = df.where(df['Variant_Classification'] != 'Silent') #creates a new dataframe where the data within the column 'Variant_Classification' is not equal to 'Silent'

  df = non_silent.dropna(subset=['Variant_Classification']) #Drops all the rows that are missing at least one element
  
  non_01_barcodes = df[~df['Tumor_Sample_Barcode'].str.contains(PRIMARY_TUMOR_PATIENT_ID_REGEX)]
  #TODO: Double check that the extra ['Tumor_Sample_Barcode'] serves no purpose
  df = df.drop(non_01_barcodes.index)
  print(df)
  shortened_patients = df['Tumor_Sample_Barcode'].str.extract(SHORTEN_PATIENT_REGEX, expand=False)
  df['identifier'] = shortened_patients
  
  gene_mutation_df = df.groupby(['Hugo_Symbol']).apply(mutations_for_gene)
  gene_mutation_df.columns = gene_mutation_df.columns.str.strip()
  gene_mutation_df.set_index(['Hugo_Symbol', 'patient'], inplace=True)
  gene_mutation_df = gene_mutation_df.reset_index()
  gene_patient_mutations = gene_mutation_df.pivot(index='Hugo_Symbol', columns='patient', values='mutated')
  
  return gene_patient_mutations.transpose().fillna(0)

これは、スクリプトが読み込むcsvファイルです。

identifier,Hugo_Symbol,Tumor_Sample_Barcode,Variant_Classification,patient
1,patient,a,Silent,6
22,mutated,d,e,7
1,Hugo_Symbol,f,g,88

スクリプトはこのエラーを出します:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-60-3f9c00f320bc> in <module>
----> 1 prep_data('test.csv')

<ipython-input-59-2a67d5c44e5a> in prep_data(mutation_path)
     21     display(gene_mutation_df)
     22     gene_mutation_df.columns = gene_mutation_df.columns.str.strip()
---> 23     gene_mutation_df.set_index(['Hugo_Symbol', 'patient'], inplace=True)
     24     gene_mutation_df = gene_mutation_df.reset_index()
     25     gene_patient_mutations = gene_mutation_df.pivot(index='Hugo_Symbol', columns='patient', values='mutated')

e:\Anaconda3\lib\site-packages\pandas\core\frame.py in set_index(self, keys, drop, append, inplace, verify_integrity)
   4546 
   4547         if missing:
-> 4548             raise KeyError(f"None of {missing} are in the columns")
   4549 
   4550         if inplace:

KeyError: "None of ['Hugo_Symbol', 'patient'] are in the columns"

以前、私はこれをその行として持っていました

   gene_mutation_df.index.set_names(['Hugo_Symbol', 'patient'], inplace=True)

しかし、それはまた、set_nameの長さが1つの引数を期待しているが2つを得ているというエラーを与えました

どんな助けでも大歓迎です

スクリプトの代わりにcsvデータが変更され、どういうわけかスクリプトがset_indexの代わりにset_namesで動作するのであれば私は本当に好きです

トレントン・マッキニー
  • 問題は次のとおりです。
    • gene_mutation_df = df.groupby(['Hugo_Symbol']).apply(mutations_for_gene)
      • 'Hugo_Symbolはに使用されるためgroupby、列ではなくインデックスに含まれるようになりました
    • サンプルデータの場合、列のない空のデータフレームが作成されています。

    gene_mutation_df = df.groupby(['Hugo_Symbol']).apply(mutations_for_gene)
    print(gene_mutation_df)  # print the dataframe to see what it looks like
    print(gene_mutation_df.info())  # print the information for the dataframe
    gene_mutation_df.columns = gene_mutation_df.columns.str.strip()
    gene_mutation_df.set_index(['Hugo_Symbol', 'patient'], inplace=True)

# output

Empty DataFrame
Columns: [identifier, Hugo_Symbol, Tumor_Sample_Barcode, Variant_Classification, patient]
Index: []
Empty DataFrame
Columns: []
Index: []


<class 'pandas.core.frame.DataFrame'>
Index: 0 entries
Empty DataFrameNone

インデックスをリセットする

  • インデックスをリセットするとHugo_Symbol、再び列が作成されます
  • データフレームが空でない限り、KeyErrorを解決する必要があります。
    gene_mutation_df = gene_mutation_df.reset_index()  # try adding this line
    gene_mutation_df.set_index(['Hugo_Symbol', 'patient'], inplace=True)

追加メモ

  • 数行のコードがあり、データフレームが空になる可能性があります
    • non_01_barcodes = df[~df['Tumor_Sample_Barcode'].str.contains(PRIMARY_TUMOR_PATIENT_ID_REGEX)]
    • shortened_patients = df['Tumor_Sample_Barcode'].str.extract(SHORTEN_PATIENT_REGEX, expand=False)
    • gene_mutation_df = df.groupby(['Hugo_Symbol']).apply(mutations_for_gene)

データフレームが空かどうかをテストします

  • .emptyデータフレームが空かどうかを判断するために使用します
def prep_data(mutation_path):
    df = pd.read_csv(mutation_path, low_memory=True, dtype=str, header = 0)#Line 24 reads in a line memory csv file from the given path and parses it based on '\t' delimators, and casts the data to str
    
    df.columns = df.columns.str.strip()  # clean the column names here if there is leading or trailing whitespace.
    
    df = df[~df['Hugo_Symbol'].str.contains('Hugo_Symbol')] #analyzes the 'Hugo_Symbol' heading within the data and makes a new dataframe where any row that contains 'Hugo_Symbol' is dropped

    df['Hugo_Symbol'] = '\'' + df['Hugo_Symbol'].astype(str) # Appends ''\'' to all the data remaining in that column

    df['Tumor_Sample_Barcode'] = df['Tumor_Sample_Barcode'].str.strip() #strips away whitespace from the data within this heading
    non_silent = df.where(df['Variant_Classification'] != 'Silent') #creates a new dataframe where the data within the column 'Variant_Classification' is not equal to 'Silent'

    df = non_silent.dropna(subset=['Variant_Classification']) #Drops all the rows that are missing at least one element

    non_01_barcodes = df[~df['Tumor_Sample_Barcode'].str.contains(PRIMARY_TUMOR_PATIENT_ID_REGEX)]
    #TODO: Double check that the extra ['Tumor_Sample_Barcode'] serves no purpose
    df = df.drop(non_01_barcodes.index)
    print(df)
    shortened_patients = df['Tumor_Sample_Barcode'].str.extract(SHORTEN_PATIENT_REGEX, expand=False)
    df['identifier'] = shortened_patients

    gene_mutation_df = df.groupby(['Hugo_Symbol']).apply(mutations_for_gene)
    
    gene_mutation_df = gene_mutation_df.reset_index()  # reset the index here
    
    print(gene_mutation_df)
    
    if gene_mutation_df.empty:  # check if the dataframe is empty
        print('The dataframe is empty')
        
    else:
    
#         gene_mutation_df.set_index(['Hugo_Symbol', 'patient'], inplace=True)  # this is not needed, pivot won't work if you do this
#         gene_mutation_df = gene_mutation_df.reset_index()  # this is not needed, the dataframe was reset already
        gene_patient_mutations = gene_mutation_df.pivot(index='Hugo_Symbol', columns='patient', values='mutated')  # values needs to be a column in the dataframe

        return gene_patient_mutations.transpose().fillna(0)

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

Pythonは、ファイルが存在するときにファイルが存在するとは見なしません

分類Dev

Pythonで文字列をフォーマットすると、ファイルが見つかりませんというエラーが発生します

分類Dev

Pythonでファイルが見つかりませんエラー、cmdにエラーはありません

分類Dev

Ansible-python3.5を試したときにVirtualenv実行可能ファイルが見つかりません

分類Dev

マシンをデプロイしてPythonファイルを実行するsshは、存在していてもエラーが見つかりません

分類Dev

Pythonモジュールが見つかりませんが、フォルダーに存在します

分類Dev

EclipseでPythonスクリプトを実行しようとしたときに、「NameError:モジュールmayaのファイルが見つかりません」

分類Dev

Pythonのfpdfは、フォントがインストールされているにもかかわらず、「RuntimeError:TTFフォントファイルが見つかりません:C:\ Windows \ Fonts \ DejaVuSansCondensed.ttf」と応答します。

分類Dev

Python-Pandasはファイルを見つけることができませんが、numpyはできます

分類Dev

Pythonの「open()」は「ファイルが見つかりません」に対して異なるエラーをスローします-両方の例外をどのように処理しますか?

分類Dev

Pythonはcsvファイルで文字列を見つけることができません

分類Dev

Python3のtempfile.TemporaryDirectory()にファイルが見つかりません

分類Dev

"exec:" python ":実行可能ファイルが$ PATHに見つかりません

分類Dev

txtファイルで「キーワード」が見つかるまで行をスキップして残りをcsvとして保存するにはどうすればよいですか?Python

分類Dev

ディレクトリフォルダ内のフォルダにあるPythonテキストファイルが見つかりません

分類Dev

Tkinterを使用してPythonで別のファイルから関数にアクセスするにはどうすればよいですか。特定の問題の解決策が見つかりません

分類Dev

Python / CSV-ファイルが見つかりませんエラー

分類Dev

PythonでサブディレクトリをナビゲートするときにOSErrorファイルが見つかりませんか?

分類Dev

PythonでUnixに存在するcsvファイルを読み取ることができません

分類Dev

Pythonでsubprocess.call( 'dir')を使用するときに指定されたファイルが見つかりません

分類Dev

Pythonでsubprocess.call( 'dir'、shell = True)を使用するときに指定されたファイルが見つかりません

分類Dev

システムにPython実行可能ファイルが見つかりませんでした、Titanium

分類Dev

kubernetes python apiに接続できません-.kube / configファイルが見つかりません

分類Dev

Pythonがファイル内の文字列を見つけることができません

分類Dev

Pythonカスタムモジュールが見つかりませんが、すでに存在しています

分類Dev

Python実行可能ファイルが見つかりません

分類Dev

ファイル<Python.h>が見つかりません

分類Dev

SeleniumとPythonを使用してGoogleにログインするためのパスワードフィールドが見つかりません

分類Dev

ファイルが存在するにもかかわらず、モックビルドが「sh:/ usr / bin / python2:そのようなファイルまたはディレクトリはありません」で失敗する

Related 関連記事

  1. 1

    Pythonは、ファイルが存在するときにファイルが存在するとは見なしません

  2. 2

    Pythonで文字列をフォーマットすると、ファイルが見つかりませんというエラーが発生します

  3. 3

    Pythonでファイルが見つかりませんエラー、cmdにエラーはありません

  4. 4

    Ansible-python3.5を試したときにVirtualenv実行可能ファイルが見つかりません

  5. 5

    マシンをデプロイしてPythonファイルを実行するsshは、存在していてもエラーが見つかりません

  6. 6

    Pythonモジュールが見つかりませんが、フォルダーに存在します

  7. 7

    EclipseでPythonスクリプトを実行しようとしたときに、「NameError:モジュールmayaのファイルが見つかりません」

  8. 8

    Pythonのfpdfは、フォントがインストールされているにもかかわらず、「RuntimeError:TTFフォントファイルが見つかりません:C:\ Windows \ Fonts \ DejaVuSansCondensed.ttf」と応答します。

  9. 9

    Python-Pandasはファイルを見つけることができませんが、numpyはできます

  10. 10

    Pythonの「open()」は「ファイルが見つかりません」に対して異なるエラーをスローします-両方の例外をどのように処理しますか?

  11. 11

    Pythonはcsvファイルで文字列を見つけることができません

  12. 12

    Python3のtempfile.TemporaryDirectory()にファイルが見つかりません

  13. 13

    "exec:" python ":実行可能ファイルが$ PATHに見つかりません

  14. 14

    txtファイルで「キーワード」が見つかるまで行をスキップして残りをcsvとして保存するにはどうすればよいですか?Python

  15. 15

    ディレクトリフォルダ内のフォルダにあるPythonテキストファイルが見つかりません

  16. 16

    Tkinterを使用してPythonで別のファイルから関数にアクセスするにはどうすればよいですか。特定の問題の解決策が見つかりません

  17. 17

    Python / CSV-ファイルが見つかりませんエラー

  18. 18

    PythonでサブディレクトリをナビゲートするときにOSErrorファイルが見つかりませんか?

  19. 19

    PythonでUnixに存在するcsvファイルを読み取ることができません

  20. 20

    Pythonでsubprocess.call( 'dir')を使用するときに指定されたファイルが見つかりません

  21. 21

    Pythonでsubprocess.call( 'dir'、shell = True)を使用するときに指定されたファイルが見つかりません

  22. 22

    システムにPython実行可能ファイルが見つかりませんでした、Titanium

  23. 23

    kubernetes python apiに接続できません-.kube / configファイルが見つかりません

  24. 24

    Pythonがファイル内の文字列を見つけることができません

  25. 25

    Pythonカスタムモジュールが見つかりませんが、すでに存在しています

  26. 26

    Python実行可能ファイルが見つかりません

  27. 27

    ファイル<Python.h>が見つかりません

  28. 28

    SeleniumとPythonを使用してGoogleにログインするためのパスワードフィールドが見つかりません

  29. 29

    ファイルが存在するにもかかわらず、モックビルドが「sh:/ usr / bin / python2:そのようなファイルまたはディレクトリはありません」で失敗する

ホットタグ

アーカイブ