3 回答
TA贡献2019条经验 获得超9个赞
用于DataFrame.select_dtypes
获取数字列并减去DataFrame.sub
with axis=1
:
df1 = df.select_dtypes(np.number).sub(df.median(axis=1), axis=0)
print (df1)
col1 col2 col3 col4 col5
0 -18.0 11.0 59.0 -8.0 0.0
1 -1.0 -2.0 2.0 0.0 6.0
2 -11.0 -4.0 19.0 0.0 25.0
3 -4.0 -7.0 38.0 49.0 0.0
4 -24.0 1.0 -35.0 0.0 4.0
5 0.0 -33.0 -34.0 13.0 16.0
如果需要分配回输出使用:
cols = df.select_dtypes(np.number).columns
df[cols] = df[cols].sub(df.median(axis=1), axis=0)
print (df)
sample_name group_name col1 col2 col3 col4 col5
0 s1 g1 -18.0 11.0 59.0 -8.0 0.0
1 s2 g1 -1.0 -2.0 2.0 0.0 6.0
2 s3 g1 -11.0 -4.0 19.0 0.0 25.0
3 s4 g2 -4.0 -7.0 38.0 49.0 0.0
4 s5 g2 -24.0 1.0 -35.0 0.0 4.0
5 s6 g2 0.0 -33.0 -34.0 13.0 16.0
另一个想法是通过以下方式选择没有前 2 行的所有行DataFrame.iloc:
df.iloc[:, 2:] = df.iloc[:, 2:].sub(df.median(axis=1), axis=0)
print (df)
sample_name group_name col1 col2 col3 col4 col5
0 s1 g1 -18.0 11.0 59.0 -8.0 0.0
1 s2 g1 -1.0 -2.0 2.0 0.0 6.0
2 s3 g1 -11.0 -4.0 19.0 0.0 25.0
3 s4 g2 -4.0 -7.0 38.0 49.0 0.0
4 s5 g2 -24.0 1.0 -35.0 0.0 4.0
5 s6 g2 0.0 -33.0 -34.0 13.0 16.0
TA贡献1840条经验 获得超5个赞
我只允许自己使用数字部分
import pandas as pd
# Generate sample data
data = {
"sample_name": ["s1", "s2", "s3", "s4", "s5", "s6"],
"group_name": ["g1", "g1", "g1", "g2", "g2", "g2"],
'col1':[1, 22, 3, 45, 31, 53],
'col2':[30, 21, 10, 42, 56, 20],
'col3':[78, 25, 33, 87, 20, 19],
'col4':[11, 23, 14, 98, 55, 66],
'col5':[19, 29, 39, 49, 59, 69],
}
keys = ['col1','col2','col3','col4','col5']
df = pd.DataFrame(data)
print(df)
# calculate medians of each row
median_ls = list(df.median(axis=1))
# [19.0, 23.0, 14.0, 49.0, 55.0, 53.0]
print(median_ls)
print(df[keys].subtract(median_ls, axis=0))
结果:
col1 col2 col3 col4 col5
0 -18.0 11.0 59.0 -8.0 0.0
1 -1.0 -2.0 2.0 0.0 6.0
2 -11.0 -4.0 19.0 0.0 25.0
3 -4.0 -7.0 38.0 49.0 0.0
4 -24.0 1.0 -35.0 0.0 4.0
5 0.0 -33.0 -34.0 13.0 16.0
添加回答
举报