【问题标题】:Reordering groups of values per data frame row?重新排序每个数据框行的值组?
【发布时间】:2019-06-19 04:06:06
【问题描述】:

假设我有一个包含如下列的数据框:

x_0, x_1, y_0, y_1, z_0, z_1

现在,值可以是任何东西,跨越 x、y、z,没有模式。 对于每一行,我想将三个字母 (x,y,z) 的值对 (0, 1) 从最小的“1”重新分配到最大的“1”。

示例行(括号便于阅读):

x_0, x_1, y_0, y_1, z_0, z_1

 (5    6)    (4    2)    (6    1)

会变成:

x_0, x_1, y_0, y_1, z_0, z_1

 6    1    4    2    5    6

我在阅读文档时遇到了麻烦,无法找到一种方法来做到这一点,而不会真的很草率。似乎在迭代行时我不应该更改值,但这就是我想要做的。当我尝试在 SO 上搜索“每行重新排序行值”时,我仍然只得到“重新排序行”结果。

【问题讨论】:

    标签: python-3.x pandas dataframe


    【解决方案1】:

    您可以将行转换为二维数组,按第二列排序并将其重新整形为单行。

    #This is your dataFrame:
    columns = ["x_0", "x_1", "y_0", "y_1", "z_0", "z_1"]
    data = np.array([5,6,4,2,6,1]).reshape(-1,6))
    df = pd.DataFrame(data=data,columns=columns)
    
    #Output
            x_0 x_1 y_0 y_1 z_0 z_1
      0      6   1   4   2   5  6
    
    #Select your row, in this case row=0; get the values as a numpy array and reshape it to a 2D array
    row=0
    M = df.iloc[row].values
    M = M.reshape(-1,2)
    
    #Output
    array([[6, 1],
           [4, 2],
           [5, 6]])
    
    #Create a temporary dataframe that you can use to sort by second column (i.e. column 1)
    df_temp = pd.DataFrame(M).sort_values(by=1)
    
    #Output
    
        0   1
    0   6   1
    1   4   2
    2   5   6
    
    #Get the sorted values back to a numpy 2D array and reshape it;
    df_temp.values.reshape(-1,6)
    
    #Output
    array([[6, 1, 4, 2, 5, 6]])
    
    #And here you are
    df.iloc[0] = df_temp.values.reshape(-1,6)
    
    #Output
        x_0 x_1 y_0 y_1 z_0 z_1
    0   6    1   4   2   5   6
    

    你可以把它们放在一行中:

    df.iloc[0] = pd.DataFrame(df.iloc[0].values.reshape(-1,2)).sort_values(by=1).values.reshape(-1,6)
    

    【讨论】:

      猜你喜欢
      • 2020-04-20
      • 2021-06-13
      • 2023-03-10
      • 1970-01-01
      • 2020-06-17
      • 1970-01-01
      • 2023-01-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多