gpt4 book ai didi

python - 将 Pandas 数据框中的 2 个类别的值计入数据透视表

转载 作者:太空宇宙 更新时间:2023-11-04 02:28:07 25 4
gpt4 key购买 nike

Here是一个引用,我已经找到了做类似的操作但不准确。

我拥有的是:
后面的数据框。格式:

    Tweets                                                   Classified     FreqWord
calm director day science meetings nasal talk cutting edge remote sensing research drought veg fluorescence calm love Positive drought
love thought drought Positive drought
reign mother kerr funny none tried make come back drought Positive drought
wonder could help thai market b post reuters drought devastates south europe crops Negative drought
wonder could help thai market b post reuters drought devastates south europe crops Negative crops
wonder could help thai market b post reuters drought devastates south europe crops Negative crops
wonder could help thai market b post reuters drought devastates south europe crops Negative business
every child safe drinking water thank uk aid providing suppo ensure children rights drought Positive drought
every child safe drinking water thank uk aid providing suppo ensure children rights drought Positive water

Dataframe

我需要的是:
数据透视表中的数据框,其中索引为 Classified,列为 FreqWord,值需要为推文出现次数,分类为该常用词。简而言之,类似于 foll。

Classified  drought crops   business    water
Positive 5 0 0 1
Negative 1 2 1 0

另请注意
对于这个数据集,我有更多的“常用词”和“分类”

最佳答案

你可以这样做:

pd.crosstab(df.Classified, df.FreqWord)

输出

FreqWord    business  crops  drought  water
Classified
Negative 1 2 1 0
Positive 0 0 4 1

或者get_dummies:

df_out = pd.get_dummies(df[['Classified','FreqWord']], columns=['FreqWord'])\
.set_index('Classified').sum(level=0)
df_out.columns = df_out.columns.str.split('_').str[1]

输出:

            business  crops  drought  water
Classified
Positive 0 0 4 1
Negative 1 2 1 0

而且,如果您愿意,可以重置_index:

df_out.reset_index()

Classified business crops drought water
0 Positive 0 0 4 1
1 Negative 1 2 1 0

关于python - 将 Pandas 数据框中的 2 个类别的值计入数据透视表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49857432/

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