列出python中列的共现数

问题描述 投票:0回答:3

我的数据框包含3个温度值和一个目标值。我希望基于目标值在温度上达到最大共现值。示例数据帧:

                 Index  Temp 1  Temp 2  Temp 3  Target 


                     1      62      66      52    0.24
                     2      62      66      62    0.28
                     3      50      69      52    0.25
                     4      62      66      62    0.28
                     5      50      69      52    0.25
                     6      62      66      62    0.28
                     7      62      66      52    0.24

我想要输出表:

                       temprature         target      counts
                    Temp1 Temp2 Temp3      0.24          2
                    Temp1 Temp2 Temp3      0.28          3
                    Temp1 Temp2 Temp3      0.25          2

我尝试了交叉表(http://pandas.pydata.org/pandas-docs/stable/generated/pandas.crosstab.html),它给了我所有的组合,我只想要最大或不止一个共现值。因为我的实际数据有数千行和30列。

python pandas dataframe
3个回答
0
投票

你可以使用pivot_tablecrosstab,最后只需要stack

df.pivot_table(index=['Temp1','Temp2','Temp3'],columns='Target',values='Index',aggfunc='count').stack().reset_index()
Out[1109]: 
   Temp1  Temp2  Temp3  Target    0
0     50     69     52    0.25  2.0
1     62     66     52    0.24  2.0
2     62     66     62    0.28  3.0

0
投票

这是通过pd.DataFrame.groupby的一种方式:

temp_cols = ['Temp1', 'Temp2', 'Temp3']

result = df.groupby('Target', as_index=False)
           .agg(dict(**{k: 'max' for k in temp_cols}, **{'Index': 'count'}))

#    Target  Temp1  Temp2  Temp3  Index
# 0    0.24     62     66     52      2
# 1    0.25     50     69     52      2
# 2    0.28     62     66     62      3

0
投票

您可以单独在数据框上执行pivot_table并将它们连接在一起。

这就是我做到的。

`df = pd.DataFrame({'Temp1':[62,62,50,62,50,62,62],
    'Temp2':[66,66,69,66,69,66,66],
    'Temp3':[52,62,52,62,52,62,52],
    'Target':[0.24,0.28,0.25,0.28,0.25,0.28,0.24]})

df1 = pd.pivot_table(df, values=['Target'],
    index=['Temp1','Temp2','Temp3']).\
    rename(columns={'Target':'target'})
df2 = pd.pivot_table(df,
    index=['Temp1','Temp2','Temp3'],
    aggfunc='count').rename(columns={'Target':'counts'})

df = df1.join(df2)
print(df)`

output

© www.soinside.com 2019 - 2024. All rights reserved.