[英]Apply function on Pandas dataframe
I'm a newbie to pandas dataframe, and I wanted to apply a function to each column so that it computes for each element x, x/max of column. 我是pandas数据帧的新手,我想为每个列应用一个函数,以便计算每个元素的x,x / max列。
I referenced this question, but am having trouble accessing the maximum of each column. 我引用了这个问题,但无法访问每列的最大值。 Thanks in advance Pandas DataFrame: apply function to all columns
在此先感谢Pandas DataFrame:将函数应用于所有列
Input: 输入:
A B C D
0 8 3 5 8
1 9 4 0 4
2 5 4 3 8
3 4 8 5 1
Output: 输出:
A B C D
0 8/9 3/8 5/5 8/8
1 9/9 4/8 0/5 4/8
2 5/9 4/8 3/5 8/8
3 4/9 8/8 5/5 1/8
Something like this should work: 这样的事情应该有效:
>>> from pandas import DataFrame
>>>
>>> df = DataFrame({"A": [8,9,5,4], "B": [3,4,4,8], "C": [5,0,3,5], "D": [8,4,8,1]})
>>> df.max()
A 9
B 8
C 5
D 8
>>> (df * 1.0)/df.max()
A B C D
0 0.888889 0.375 1.0 1.000
1 1.000000 0.500 0.0 0.500
2 0.555556 0.500 0.6 1.000
3 0.444444 1.000 1.0 0.125
Note that I multiplied df
by 1.0
so that it didn't consists of int
s anymore ( .astype(float)
would have worked too) to avoid integer division and a resulting DataFrame full of 0s and 1s. 请注意,我将
df
乘以1.0
使得它不再包含int
s( .astype(float)
也会起作用)以避免整数除法和结果DataFrame为0和1。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.