python - 拆分,将数据映射到 Pandas 数据框中的两列中

标签 python pandas dictionary split

我想将数据框中的数据分成两列,并使用这些数据构建新列。

我的数据框是,

dfc = pd.DataFrame( {"A": ["GT:DP:RO:QR:AO:QA:GL", "GT:DP:RO:QR:AO:QA:GL", "GT:DP:RO:QR:AO:QA:GL", "GT:DP:GL", "GT:DP:GL"], "B": ["0/1:71:43:1363:28:806:-71.1191,0,-121.278", "0/1:71:43:1363:28:806:-71.1191,0,-121.278", "0/1:71:43:1363:28:806:-71.1191,0,-121.278", "1/1:49:-103.754,0,-3.51307", "1/1:49:-103.754,0,-3.51307"]} )

我想要名为 GT、DP、RO、QR、AO、QA、GL 的各个列,其值来自列 B

我想产生输出, enter image description here

我们可以使用 a = df.A.str.split(":", expand = True)b = df.B.str.split(":", expand = True) 得到两个单独的数据框。这些可以与 c = pd.merge(a, b, left_index = True, right_index = True) 合并以获得所有需要的数据。但是,不是预期的格式。 enter image description here

有什么建议吗?我认为更好的方法是在 AB 两列上使用 split 然后创建一个包含值的 dictA 作为键,B 作为值。然后可以将此列转换为数据框。 谢谢

最佳答案

使用 OrderedDict 在创建数据帧的两个相关列的 dict 映射后保留顺序 : ",扁平化为一个列表

稍后将其提供给数据框构造函数。

from collections import OrderedDict

L = dfc.apply(
    lambda x: OrderedDict(zip(x['A'].split(':'), x['B'].split(':'))), 1).tolist()
pd.DataFrame(L)

enter image description here

关于python - 拆分,将数据映射到 Pandas 数据框中的两列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41375297/

相关文章:

python - 使用 PyScripter 执行带有参数的 python 文件

python - 如何使用滑动窗口调整 PyTorch 张量的大小?

python - 如何从 Pandas 数据框中删除互惠记录?

python - 如何通过检查列表中的子级索引值来过滤 Pandas 数据帧的行?

python - django mysql连接问题

python - sklearn : use Pipeline in a RandomizedSearchCV?

python - 如何仅使用逗号之前第一个出现的单词替换数据框文本列

java - 将不同类类型的对象作为 java 中映射中的值进行处理

ms-access - 字典使所有键的值等于最近的键/值相加

Swift 在字典中允许 nil