簡體   English   中英

TypeError:遍歷每一行以獲得特定列值時,字符串索引必須是整數

[英]TypeError: string indices must be integers when iterrating over each row to get a specific column value

我想對每個基因進行時間線性回歸分析,采用 model 中存在的所有變量,因此使用所有基因。

在df5中,x軸代表“基因符號”,y軸代表“時間”。

import pandas as pd
import numpy as np
import plotly.express as px
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split

# Split data into training and test splits
train_idx, test_idx = train_test_split(df5.index, test_size=.25, random_state=0)
df5["split"] = "train"
df5.loc[test_idx, "split"] = "test"

# Inputs and targets
X = df5.iloc[:, 1:-1]
y = df5.iloc[:, 0]

X_train = df5.loc[train_idx, ["4", "8", "12", "24", "48"]]
y_train = df5.loc[train_idx, "0"]

# Linear regression prediction
model = LinearRegression()
model.fit(X_train, y_train)
df5['prediction'] = model.predict(X)

當我想使用y=i["prediction"]y變量設置為每一行的prediction列值時,我得到一個類型錯誤。

# Scatter plot
for i, j in df5.iterrows():
  for col in df5.columns:
    fig = px.scatter(df5[col], x=df5.iloc[:,0], y=i["prediction"], marginal_x='histogram', marginal_y='histogram', color='split', trendline='ols')
    fig.update_traces(histnorm='probability', selector={'type':'histogram'})
    fig.add_shape(type="line", line=dict(dash='dash'), x0=y.min(), y0=y.min(), x1=y.max(), y1=y.max())
    fig.show()

追溯:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-395-6ef08290c83a> in <module>()
      2 for i, j in df5.iterrows():
      3   for col in df5.columns:
----> 4     fig = px.scatter(df5[col], x=df5.iloc[:,0], y=i["prediction"], marginal_x='histogram', marginal_y='histogram', color='split', trendline='ols')
      5     fig.update_traces(histnorm='probability', selector={'type':'histogram'})
      6     fig.add_shape(type="line", line=dict(dash='dash'), x0=y.min(), y0=y.min(), x1=y.max(), y1=y.max())

TypeError: string indices must be integers

數據:

df5.head().to_dict()

{'0': {'DNAJB6 /// TMEM135': 0.30131649339447103,
  'DNAJC14': 0.2255444383216058,
  'DNAJC15': 0.25789169794229455,
  'DNAJC30': 0.11388797858763917,
  'DNAJC9': 0.11205541676885071},
 '12': {'DNAJB6 /// TMEM135': 0.28354614480145346,
  'DNAJC14': 0.2343653660720247,
  'DNAJC15': 0.2406210529534205,
  'DNAJC30': 0.11229754447748205,
  'DNAJC9': 0.12045170255898871},
 '24': {'DNAJB6 /// TMEM135': 0.27395808285292367,
  'DNAJC14': 0.2246018336027369,
  'DNAJC15': 0.22347959865906092,
  'DNAJC30': 0.11379897713291527,
  'DNAJC9': 0.10622530623273815},
 '4': {'DNAJB6 /// TMEM135': 0.2949284643966144,
  'DNAJC14': 0.22905481299223704,
  'DNAJC15': 0.22312009403152122,
  'DNAJC30': 0.13114878202076288,
  'DNAJC9': 0.12991396178392187},
 '48': {'DNAJB6 /// TMEM135': 0.289873135093664,
  'DNAJC14': 0.2349502215468218,
  'DNAJC15': 0.17706771640592167,
  'DNAJC30': 0.10857074282633467,
  'DNAJC9': 0.13001391250069522},
 '8': {'DNAJB6 /// TMEM135': 0.2794865791356734,
  'DNAJC14': 0.22228815371920396,
  'DNAJC15': 0.22912018863353348,
  'DNAJC30': 0.11799998627920205,
  'DNAJC9': 0.10520854728987451}}

第一:如果錯誤告訴你哪一行出了問題,那么首先你可以使用 print()、print(type(...)) 等來檢查你在這一行的變量中有什么。

看來您使用了錯誤的變量。 我認為錯誤是i["prediction"]因為i應該是index of row ,而不是row with data 也許如果您for index, row in df5.iterrow()使用更具可讀性的變量,而不是for i,j in df.iterrow()那么您會看到運行index["prediction"]而不是row["prediction"]


但坦率地說,我不明白你對 plot 的嘗試。

x=df5.iloc[:,0]應該在列中給出所有數據,而不是在行中,但是y=row["prediction"]應該給出一行中的單個值。 這沒有道理。 您應該使用y=df5["prediction"]並在沒有df5.iterrows()的情況下運行它 - 甚至只使用列名而不是數據px.scatter(df5, x=col, y="prediction", ...)

for col in ["4", "8", "12", "24", "48"]:  # without "0"
    fig = px.scatter(df5, x=col, y="prediction", marginal_x='histogram', marginal_y='histogram', color='split')#, trendline='ols')
    fig.update_traces(histnorm='probability', selector={'type':'histogram'})
    fig.add_shape(type="line", line=dict(dash='dash'), x0=y.min(), y0=y.min(), x1=y.max(), y1=y.max())
    fig.show()

完整的工作代碼和代碼中的示例數據 - 所以每個人都可以簡單地復制和運行它

順便說一句:它在單獨的頁面上打開每個 plot。 我不得不在scatter中跳過trendline='ols' ,因為它給了我錯誤ImportError: cannot import name '_centered' from 'scipy.signal.signaltools' (/usr/local/lib/python3.8/dist-packages/scipy/signal/signaltools.py)

data = {'0': {'DNAJB6 /// TMEM135': 0.30131649339447103,
  'DNAJC14': 0.2255444383216058,
  'DNAJC15': 0.25789169794229455,
  'DNAJC30': 0.11388797858763917,
  'DNAJC9': 0.11205541676885071},
 '12': {'DNAJB6 /// TMEM135': 0.28354614480145346,
  'DNAJC14': 0.2343653660720247,
  'DNAJC15': 0.2406210529534205,
  'DNAJC30': 0.11229754447748205,
  'DNAJC9': 0.12045170255898871},
 '24': {'DNAJB6 /// TMEM135': 0.27395808285292367,
  'DNAJC14': 0.2246018336027369,
  'DNAJC15': 0.22347959865906092,
  'DNAJC30': 0.11379897713291527,
  'DNAJC9': 0.10622530623273815},
 '4': {'DNAJB6 /// TMEM135': 0.2949284643966144,
  'DNAJC14': 0.22905481299223704,
  'DNAJC15': 0.22312009403152122,
  'DNAJC30': 0.13114878202076288,
  'DNAJC9': 0.12991396178392187},
 '48': {'DNAJB6 /// TMEM135': 0.289873135093664,
  'DNAJC14': 0.2349502215468218,
  'DNAJC15': 0.17706771640592167,
  'DNAJC30': 0.10857074282633467,
  'DNAJC9': 0.13001391250069522},
 '8': {'DNAJB6 /// TMEM135': 0.2794865791356734,
  'DNAJC14': 0.22228815371920396,
  'DNAJC15': 0.22912018863353348,
  'DNAJC30': 0.11799998627920205,
  'DNAJC9': 0.10520854728987451}
}

import pandas as pd
import numpy as np
import plotly.express as px
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split

df5 = pd.DataFrame(data)

# Split data into training and test splits
train_idx, test_idx = train_test_split(df5.index, test_size=.25, random_state=0)
df5["split"] = "train"
df5.loc[test_idx, "split"] = "test"

# Inputs and targets
X = df5.iloc[:, 1:-1]
y = df5.iloc[:, 0]

X_train = df5.loc[train_idx, ["4", "8", "12", "24", "48"]]
y_train = df5.loc[train_idx, "0"]

# Linear regression prediction
model = LinearRegression()
model.fit(X_train, y_train)
df5['prediction'] = model.predict(X)

for col in ["4", "8", "12", "24", "48"]:  # without "0"
    fig = px.scatter(df5, x=col, y="prediction", marginal_x='histogram', marginal_y='histogram', color='split')#, trendline='ols')
    fig.update_traces(histnorm='probability', selector={'type':'histogram'})
    fig.add_shape(type="line", line=dict(dash='dash'), x0=y.min(), y0=y.min(), x1=y.max(), y1=y.max())
    fig.show()

Plot 用於"4"

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM