我有以下数据框:
df = pd.DataFrame(list(zip([1,2],
[5,6],
[9,10],
[13,14])))
df.columns =['x_A', 'y_A', 'x_B', 'y_B']
df:
x_A y_A x_B y_B
0 1 5 9 13
1 2 6 10 14
我想划分具有相似前缀的列以获得以下结果:
df:
x y
0 1/9 5/13
1 2/10 6/14
如果可能的话,可以用一行来完成吗?
谢谢。
最佳答案
一种方法:
def divide_reduce(x):
y = x.to_numpy().astype(np.float64)
return np.divide.reduce(y, axis=1)
res = df.groupby(df.columns.str[0], axis=1).agg(divide_reduce)
print(res)
输出
x y
0 0.111111 0.384615
1 0.200000 0.428571
如果您更喜欢单行方法,您可以使用:
res = df.astype(np.float64).groupby(df.columns.str[0], axis=1).agg(np.divide.reduce, axis=1)
关于python - 从具有相似前缀的列中划分元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69780782/