【问题标题】:Frequency distribution of list against another column列表相对于另一列的频率分布
【发布时间】:2019-02-17 04:59:27
【问题描述】:

我正在尝试获取列的频率分布,该列是针对类标签的单词列表。

Label                Numbers
0                    [(a,b,c)]
0                    [(d)]
0                    [(e,f,g)]
1                    [(a,z)]
1                    [(d,x,y)]

输出应该是:

         0          1
a        1          1
b        1          0
c        1          0
d        1          1
e        1          0
f        1          0        
g        1          0
x        0          1
y        0          1
z        0          1

【问题讨论】:

  • 您的数据是pandas 还是其他格式?您的示例看起来像 pandas 数据框,但我不想做出假设。
  • @vealkind 是的,它在熊猫中。
  • 到目前为止你尝试了什么?

标签: python python-3.x python-2.7 pandas


【解决方案1】:

'Numbers' 列中的集合列表使得操作 DataFrame 非常困难(这不是整洁的数据)。解决方案是扩展DataFrame,使'Numbers' 列中只有一个数字对应'Label' 列中的一个值。假设您的数据位于名为 df 的 DataFrame 中,以下代码将执行该操作:

rows_list = []

for index, row in df.iterrows():
    for element in row['Numbers'][0]:
        dict1 = {}
        dict1.update(key=row['Label'], value=element)
        rows_list.append(dict1)

new_df = pd.DataFrame(rows_list)
new_df.columns = ['Label', 'Numbers']

结果是

  Label Numbers
0     0     a
1     0     b
2     0     c
3     0     d
4     0     e
5     0     f
6     0     g
7     1     a
8     1     z
9     1     d
10    1     x
11    1     y    

现在是旋转的问题:

print(new_df.pivot_table(index='Numbers', columns='Label', aggfunc=len,
                         fill_value=0))

结果是

Label    0  1
Numbers      
a        1  1
b        1  0
c        1  0
d        1  1
e        1  0
f        1  0
g        1  0
x        0  1
y        0  1
z        0  1

最后一行代码见first answer here

【讨论】:

  • 我的元素只显示[,元素的类型也是string。我正在从 csv 文件中读取此表,也许这就是原因。另外,我从其他一些函数(实际上它是一种模式)中获得了 Numbers 值,所以我无法更改它。但我们可以像您展示的那样处理。
  • @amy:你的评论中有很多地方我不明白你的意思。希望我的代码对您有所帮助!
  • 我想说Numbers 是一个字符串,因为我正在从 csv 文件中读取数据。如果它是一个列表,则该解决方案很有帮助。
  • @amy:我明白了。在这种情况下,您需要先将字符串解析为集合列表,然后才能应用我的其余代码。下面的代码可以帮助解决这个问题:'[(a,b,c)]'.replace('[(', '').replace(')]', '').split(',') 然后您可能必须删除内部 for 循环中的 [0] 部分。
猜你喜欢
  • 2021-06-08
  • 2019-09-16
  • 2020-05-25
  • 2022-01-03
  • 1970-01-01
  • 2022-12-31
  • 2021-09-10
  • 2014-12-16
  • 2017-03-26
相关资源
最近更新 更多