列出python中列的共现数

2024-03-28 23:52:25 发布

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

我的数据框包含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列。你知道吗


Tags: 数据示例targetpandasindex温度tempcounts
3条回答

这里有一种通过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

您可以使用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

您可以分别对数据帧执行透视表,并将它们连接在一起。你知道吗

我是这样做的。你知道吗

`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

相关问题 更多 >