可以说我有一个数据列,其中包含诸如:
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上搜索“每行的行值重新排序”时,我仍然只得到“重新排序行”结果。
答案 0 :(得分:0)
您可以将行转换为2D数组,然后按第二列对其进行排序,然后将其整形为单行。
#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
您可以将所有togheter放在一行中:
df.iloc[0] = pd.DataFrame(df.iloc[0].values.reshape(-1,2)).sort_values(by=1).values.reshape(-1,6)