对python中dataframe的每个元素应用相同的计算

2024-04-28 07:13:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个这样的数据帧。你知道吗

          user  tag1  tag2  tag3
0  Roshan ghai   0.0   1.0   1.0
1    mank nion   1.0   1.0   2.0
2   pop rajuel   2.0   0.0   1.0
3   random guy   2.0   1.0   1.0

我必须对每一行进行计算。对于每个元素x

x =(( specific tag's count for that user ##that element itself##))/ max no. of count of that tag ##max value of that column##)) * (ln(no. of total user ##lenth of df##)/(no. of of user having that tag ##no. of user having non 0 count for that particular tag or column ##))

我用###来描述这个特殊的值。我必须为dataframe的每个元素做这件事,什么是最有效的方法,因为我有大量的元素。我用的是python2.7。 输出:

          user  tag1  tag2  tag3
0  Roshan ghai     0  .287     0
1    mank nion  .143  .287     0
2   pop rajuel  .287     0     0
3   random guy  .287  .287     0

我刚刚用了我写的mank nion和tag1的公式 x=((1.0)/2.0)*(ln(4/3)=.143。你知道吗


Tags: ofno元素thattagcountpopnion
2条回答

你可以试试这个:

import io
temp = u"""          user  tag1  tag2  tag3
0  Roshan-ghai   0.0   1.0   1.0
1    mank-nion   1.0   1.0   2.0
2   pop-rajuel   2.0   0.0   1.0
3   random-guy   2.0   1.0   1.0"""
df = pd.read_csv(io.StringIO(temp), delim_whitespace=True)

maxtag1 = df.tag1.max()
maxtag2 = df.tag2.max()
maxtag3 = df.tag3.max()
number_users = len(df)
number_users_tag1 = len(df[df['tag1']!=0])
number_users_tag2 = len(df[df['tag2']!=0])
number_users_tag3 = len(df[df['tag3']!=0])
liste_values = [maxtag1,maxtag2,maxtag3,number_users,number_users_tag1,number_users_tag2,number_users_tag3]

然后创建一个函数,将行和这些值作为输入,并输出所需的三个值。并使用apply

output = df.apply(lambda x: yourfunction(x, list_values))

可以首先通过^{}选择没有第一列的所有值。然后使用^{}^{}的非0值和^{}

import pandas as pd
import numpy as np

print (df.ix[:, 'tag1':].max())
tag1    2.0
tag2    1.0
tag3    2.0
dtype: float64

print ((df.ix[:, 'tag1':] != 0).sum())
tag1    3
tag2    3
tag3    4
dtype: int64

df.ix[:, 'tag1':] = (df.ix[:, 'tag1':] / df.ix[:, 'tag1':].max() * 
                    (np.log(len(df) / (df.ix[:, 'tag1':] != 0).sum())))

print (df)
          user      tag1      tag2  tag3
0  Roshan-ghai  0.000000  0.287682   0.0
1    mank-nion  0.143841  0.287682   0.0
2   pop-rajuel  0.287682  0.000000   0.0
3   random-guy  0.287682  0.287682   0.0

使用^{}的另一种解决方案:

df1 = df.iloc[:, 1:]
df.iloc[:, 1:] = (df1 / df1.max() * (np.log(len(df) / (df1 != 0).sum())))
print (df)
          user      tag1      tag2  tag3
0  Roshan-ghai  0.000000  0.287682   0.0
1    mank-nion  0.143841  0.287682   0.0
2   pop-rajuel  0.287682  0.000000   0.0
3   random-guy  0.287682  0.287682   0.0

相关问题 更多 >