gpt4 book ai didi

Python Pandas : applying a specific function to each row

转载 作者:行者123 更新时间:2023-12-02 19:18:50 25 4
gpt4 key购买 nike

我正在尝试对我拥有的数据应用某种形式的标准化。我希望从数据框中的每个值中减去每行的中位数。到目前为止我所拥有的:

# 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],
}
df = pd.DataFrame(data)

# calculate medians of each row
median_ls = list(df.median(axis=1))
# [19.0, 23.0, 14.0, 49.0, 55.0, 53.0]

预期结果是:

-18,11,59,-8,0
-1,-2,2,0,6
-11,-4,19,0,25
-4,-7,38,49,0
-24,1,-35,0,4
0,-33,-34,13,16

我看过df.apply(<function>, axis=1) ,但无法计算出如何跨行迭代应用特定于行的函数的语法。

最佳答案

使用DataFrame.select_dtypes获取数字列并减去 DataFrame.subaxis=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

另一个想法是通过 DataFrame.iloc 选择没有前 2 行的所有行:

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

关于Python Pandas : applying a specific function to each row,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63336125/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com