【问题标题】:counting integers and strings differently on pandas在 pandas 上以不同方式计算整数和字符串
【发布时间】:2015-11-02 14:43:20
【问题描述】:

我是熊猫的初学者。我有两列,我将它们组合在一起。

我尝试按每个州和每个 ID 号计算每一行。我有成千上万的身份和状态,有人可以帮我解决我的问题吗?谢谢。

draft= df[["ID", "STATE" ]]

draft
Out[5]: 
           ID                                         STATE
0          11                                 chr1:100154376:G:A
1           2                                 chr1:100177723:C:T
2           9                                 chr1:100177723:C:T
3           1                                chr1:100194200:-:AA
4           8                                  chr1:10032249:A:G
5           2                                 chr1:100340787:G:A
6           1                                 chr1:100349757:A:G
7           3                                  chr1:10041186:C:A
8          10                                 chr1:100476986:G:C
9           4                                 chr1:100572459:C:T
10          5                                 chr1:100572459:C:T


chars = "TGC-"
number = {}

for item in chars:
    d = draft
    At = d.str.contains("A:" + item)
    num = At.value_counts(sort=True)
    number[item] = num
    id_num1=sd["ID"].value_counts()
    id_values1= id_num1.order()

【问题讨论】:

  • 你想要 At = d['STATE'].str.contains("A:" + char3) str 属性可用于 'Series` 而不是 DataFrame 所以你想在列上调用它
  • 还有什么是number[char3] = num?,还有你希望id_1 = d.sort("draft")["draft"]做什么? “草稿”不是d中的列
  • @EdChum 感谢您的第一条评论。好的,我删除了 id_1 部分。(我真的不知道我为什么写)。我尝试逐行分析此列,并希望同时获取 id 和 state。 ATnum = number["T"] 给了我状态的数量,但我如何将它与 id 连接起来并计算它们?

标签: python string pandas count integer


【解决方案1】:

这是我对 stackoverflow 的第一个回答。请忽略它,如果它没有意义。我不是资深的程序员——但我喜欢熊猫。我想你想做这样的事情。

import pandas as pd
import numpy as np
ids = [21,2,9,1,8,2,1,3,10,4,4]
states = ['GA','CT','AA','AG','CA','GC','CT','CT','CA','AG','AG']
draft = pd.DataFrame({'ids':ids,'state':states})
draft

d = dict()
for dex, row in draft.iterrows():
    x = row['ids']
    y = row['state']

    if y in d:
        # append the new state to the existing array at this slot
        d[y].append(x)
    else:
        # create a new array in this slot
        d[y] = [x]

带有状态和计数的新字典:

d
{'AA': [9],
 'AG': [1, 4, 4],
 'CA': [8, 10],
 'CT': [2, 1, 3],
 'GA': [21],
 'GC': [2]}

显示结果:

for key, value in d.iteritems():
     print key, len(value)

AA 1
AG 3
CA 2
GC 1
GA 1
CT 3

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-23
    • 1970-01-01
    • 2022-01-01
    • 2015-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    相关资源
    最近更新 更多