簡體   English   中英

用數組替換pandas數據幀的一部分

[英]Replace part of a row of a pandas dataframe with an array

我有一個如下所示的數據幀df1

     Sample_names    esv0     esv1   esv2   ...    esv918  esv919  esv920  esv921
0    pr1gluc8NH1     2.1      3.5   6222   ...         0       0       0       0
1    pr1gluc8NH2  3189.0     75.0   9045   ...         0       0       0       0
2  pr1gluc8NHCR1     0.0   2152.0  12217   ...         0       0       0       0
3  pr1gluc8NHCR2     0.0  17411.0   1315   ...         0       1       0       0
4     pr1sdm8NH1   365.0      7.0   4117   ...         0       0       0       0
5     pr1sdm8NH2  4657.0     18.0  13520   ...         0       0       0       0
6   pr1sdm8NHCR1     0.0    139.0   3451   ...         0       0       0       0
7   pr1sdm8NHCR2  1130.0   1439.0   4163   ...         0       0       0       0

我想對行執行一些操作並通過for循環替換它們。

for i in range(len(df1)):
     x=df1.iloc[i].values  ### gets all the values corresponding to each row
     x=np.vstack(x[1:]).astype(np.float) ####converts object type to a regular 2D array for all row elements except the first, which is a string.
     x=x/np.sum(x) ###normalize to 1
     df1.iloc[i,1:]=x   ###this is the step that should replace part of the old row with the new array.

但是有了這個,我得到一個錯誤“ValueError:使用ndarray設置時必須具有相等的len鍵和值”。 x確實與df1 - 1的每一行具有相同的長度(我不想替換第一列,Sample_names)

我也試過df1=df1.replace(df1.iloc[i,1:],x) 這給出了TypeError:value參數必須是標量,dict或Series。

我將不勝感激任何想法如何做到這一點。

謝謝。

您需要重塑x數組的形狀(n, 1)因為它的形狀是(n, 1) ,其中n是所有類似esv的列的長度。

更改行: df1.iloc[i, 1:] = x to

df1.iloc[i, 1:] = x.squeeze()

暫無
暫無

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

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