【发布时间】:2021-11-27 19:38:42
【问题描述】:
我正在尝试做的事情:我有以下数据框。我需要捕获空间超过 4 的数据行并将信息放入单独的字典中。
例如 - 2. harry potter 和 A. test book 之间的行将被捕获,A. test book 和 F. book3 之间的行也将被捕获(所需的输出如下所示)
我无法预先定义字典的数量,因为我不知道需要多少,因为它取决于数据。
数据框示例:
name | A | space
---------------|---|------
2. harry potter| 1 | 2
jk rowling | 1 | 4
testing | 3 | 4
A. test book | 4 | 2
author1 | 4 | 4
author2 | 4 | 4
author3 | 4 | 4
F. book3 | 5 | 2
期望的输出:
dict_A = {name:'jk rowling',testing', A: '1','3', space: '4','4'}
dict_B = {name:'author1', 'author2', 'author3', A:'4','4','4', space: '4','4','4'}
我尝试过的:
lst_A =[]
for i in df["name"]:
if not i.startswith(('2.','A.','F.')):
if len(i) - len(i.lstrip()) > 3:
lst_A.append(i)
else:
if i.startswith(('2.','A.','F.')):
pass
df 作为字典:
上面的代码只为我提供了超过 4 个空格的列名中的数据 - 但是我无法将它正确地分离到单独的列表/字典中并捕获所有信息。有人能帮我指出正确的方向吗?
对于参考:df 作为字典:
{'name': {0: '2. harry potter',
1: ' jk rowling ',
2: ' testing ',
3: 'A. test book ',
4: ' author1 ',
5: ' author2 ',
6: ' author3 ',
7: 'F. book3 '},
'A': {0: 1, 1: 1, 2: 3, 3: 4, 4: 4, 5: 4, 6: 4, 7: 5},
'space': {0: 2, 1: 4, 2: 4, 3: 2, 4: 4, 5: 4, 6: 4, 7: 2}}
【问题讨论】:
-
你能提供你的数据框作为字典吗? (
df.to_dict()) -
@mozway 也将添加到问题中:
{'name': {0: '2. harry potter', 1: ' jk rowling ', 2: ' testing ', 3: 'A. test book ', 4: ' author1 ', 5: ' author2 ', 6: ' author3 ', 7: 'F. book3 '}, 'A': {0: 1, 1: 1, 2: 3, 3: 4, 4: 4, 5: 4, 6: 4, 7: 5}, 'space': {0: 2, 1: 4, 2: 4, 3: 2, 4: 4, 5: 4, 6: 4, 7: 2}} -
谢谢,我提供了a solution
标签: python python-3.x pandas dataframe dictionary