gpt4 book ai didi

python - 在 Python 中使用两个列变量将数据框转换为频率列表

转载 作者:太空狗 更新时间:2023-10-30 02:58:34 25 4
gpt4 key购买 nike

我有一个由列节点、组件和前导词组成的数据框。节点包含许多相同的值(按字母顺序排序),组件也包含许多相同的值,但被打乱了,前面的词可以是所有类型的词 - 但有些也相同。

我现在想做的是创建某种横截面/频率列表,显示链接到节点的组件和前面单词的频率。

假设这是我的 df:

node    precedingWord comp
banana the lel
banana a lel
banana a lal
coconut some lal
coconut few lil
coconut the lel

我期待一个显示每个唯一节点的频率列表,以及在给定匹配条件的其他列中找到某个值的时间,例如

det1 = a
det2 = the
comp1 = lel
comp2 = lil
comp 3 = lal

预期输出:

node    det1  det2 unspecified comp1 comp2 comp3
banana 2 1 0 2 0 1
coconut 0 1 0 1 1 1

我已经为一个变量做了这件事,但我不知道如何让 comp 列就位:

det1 = ["a"]
det2 = ["the"]

df.loc[df.preceding_word.isin(det1), "determiner"] = "det1"
df.loc[df.preceding_word.isin(det2), "determiner"] = "det2"
df.loc[df.preceding_word.isin(det1 + det2) == 0, "determiner"] = "unspecified"

# Create crosstab of the node and gender
freqDf = pd.crosstab(df.node, df.determiner)

我从 here 得到了这个答案.如果有人能解释 loc 的作用,那也会有很大帮助。


考虑到安迪的回答,我尝试了以下方法。请注意,“precedingWord”已替换为“gender”,它仅包含值 neuter、non_neuter、gender。

def frequency_list():
# Define content of gender classes
neuter = ["het"]
non_neuter = ["de"]

# Add `gender` column to df
df.loc[df.preceding_word.isin(neuter), "gender"] = "neuter"
df.loc[df.preceding_word.isin(non_neuter), "gender"] = "non_neuter"
df.loc[df.preceding_word.isin(neuter + non_neuter) == 0, "gender"] = "unspecified"

g = df.groupby("node")

# Create crosstab of the node, and gender and component
freqDf = pd.concat([g["component"].value_counts().unstack(1), g["gender"].value_counts().unstack(1)])

# Reset indices, starting from 1, not the default 0!
""" Crosstabs don't come with index, so we first set the index with
`reset_index` and then alter it. """
freqDf.reset_index(inplace=True)
freqDf.index = np.arange(1, len(freqDf) + 1)

freqDf.to_csv("dataset/py-frequencies.csv", sep="\t", encoding="utf-8")

输出接近我想要的,但不完全是:

enter image description here

  1. 交叉表没有“合并”,换句话说:首先显示 comp (component) 的行,然后显示 gender 的相同节点。
  2. 空值应为 0
  3. 所有值都应该是整数,不能是 float 。

那么,我想要的是:

enter image description here

请注意,我正在寻找最有效的答案。我实际上正在处理负载和数据负载,因此每个循环的每一秒都很重要!

最佳答案

更新:这是一个 crosstab :

In [11]: df1 = pd.crosstab(df['node'], df['precedingWord'])

In [12]: df1
Out[12]:
precedingWord a few some the
node
banana 2 0 0 1
coconut 0 1 1 1

In [13]: df2 = pd.crosstab(df['node'], df['comp'])

这显然是一种更清洁(并且对大数据更有效的算法)。

然后用 axis=1 的连接将它们粘合起来(即添加更多的列而不是添加更多的行)。

In [14]: pd.concat([df1, df2], axis=1, keys=['precedingWord', 'comp'])
Out[14]:
precedingWord comp
a few some the lal lel lil
node
banana 2 0 0 1 1 2 0
coconut 0 1 1 1 1 1 1

我可能会像这样保留它(作为一个 MultiIndex),如果你想让它变平只是不要传递键(尽管重复的单词可能有问题):

In [15]: pd.concat([df1, df2], axis=1)
Out[15]:
a few some the lal lel lil
node
banana 2 0 0 1 1 2 0
coconut 0 1 1 1 1 1 1

旁白:如果 concat 不要求在列名称存在时显式传入(作为键 kwarg),那就太好了...


原始答案

您可以使用 value_counts:

In [21]: g = df.groupby("node")

In [22]: g["comp"].value_counts()
Out[22]:
node comp
banana lel 2
lal 1
coconut lal 1
lel 1
lil 1
dtype: int64

In [23]: g["precedingWord"].value_counts()
Out[23]:
node precedingWord
banana a 2
the 1
coconut few 1
some 1
the 1
dtype: int64

将它放在一个框架中有点棘手:

In [24]: pd.concat([g["comp"].value_counts().unstack(1), g["precedingWord"].value_counts().unstack(1)])
Out[24]:
a few lal lel lil some the
node
banana NaN NaN 1 2 NaN NaN NaN
coconut NaN NaN 1 1 1 NaN NaN
banana 2 NaN NaN NaN NaN NaN 1
coconut NaN 1 NaN NaN NaN 1 1

In [25]: pd.concat([g["comp"].value_counts().unstack(1), g["precedingWord"].value_counts().unstack(1)]).fillna(0)
Out[25]:
a few lal lel lil some the
node
banana 0 0 1 2 0 0 0
coconut 0 0 1 1 1 0 0
banana 2 0 0 0 0 0 1
coconut 0 1 0 0 0 1 1

您可以在执行连接之前将列映射到 det1、det2 等,例如,如果您将映射作为字典。

In [31]: res = g["comp"].value_counts().unstack(1)

In [32]: res
Out[32]:
comp lal lel lil
node
banana 1 2 NaN
coconut 1 1 1

In [33]: res.columns = res.columns.map({"lal": "det1", "lel": "det2", "lil": "det3"}.get)

In [34]: res
Out[34]:
det1 det2 det3
node
banana 1 2 NaN
coconut 1 1 1

或者,您可以使用列表推导式(如果您没有字典或心中有特定的标签):

In [41]: res = g["comp"].value_counts().unstack(1)

In [42]: res.columns = ['det%s' % i for i, _ in enumerate(df.columns)]

关于python - 在 Python 中使用两个列变量将数据框转换为频率列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33611776/

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