[英]How to modify multiple items in a list?
I want to modify 2 things in my list.我想修改列表中的两件事。
id
has to become V1
and field1
has to become A
. id
必须成为V1
并且field1
必须成为A
。 After that I want to make a data-frame of just the dictionaries inside the_list
.之后,我想为
the_list
中的字典制作一个数据框。 This is my expected outcome:这是我的预期结果:
V1 - A
0 1 - 1
1 2 - 2
2 3 - 3
3 4 - 4
This is my_list这是我的_list
the_list = [['www.url1.com)', 1429, [{'id': 1, 'field1': None},
{'id': 2, 'field1': None}], 'www.url2.com'], ['www.url1.com)', 1429,
[{'id': 3, 'field1': None}, {'id': 4, 'field1': None}]]]
This is my current code:这是我当前的代码:
for n, i in enumerate(the_list):
if i == 'id':
the_list[n] = 'V1'
if i == 'field1':
the_list[n] = 'A'
#print(the_list)
df1 = pd.DataFrame(the_list[2])
#print(df)
I did not receive any errors, my output was the same as the current state of the_list
.我没有收到任何错误,我的 output 与 the_list 的当前
the_list
。
You can make a list comprehension and pass it to the df constructor您可以进行列表理解并将其传递给 df 构造函数
df = pd.DataFrame([
list(each_dict.values())
for complex in the_list
for each_dict in complex[2]
], columns=['V1', 'A'])
print(df)
V1 A
0 1 None
1 2 None
2 3 None
3 4 None
Notice how all the field1
values are None
, so they get read into the df as such请注意所有
field1
值是如何None
,因此它们被读入 df
Its Better to Change it Recursively to avoid the Errors Or you can use pandas rename method最好递归更改它以避免错误或者您可以使用 pandas 重命名方法
the_list = [['www.url1.com)', 1429, [{'id': 1, 'field1': None},
{'id': 2, 'field1': None}], 'www.url2.com'], ['www.url1.com)', 1429,
[{'id': 3, 'field1': None}, {'id': 4, 'field1': None}]]]
def recursiveChange(the_list_tmp):
for n, i in enumerate(the_list_tmp):
if isinstance(i, list):
the_list_tmp[n] = recursiveChange(i)
continue
if isinstance(i, dict):
if 'id' in i:
the_list_tmp[n]['V1'] = i['id']
del the_list_tmp[n]['id']
if 'field1' in i :
the_list_tmp[n]['A'] = i['field1']
del the_list_tmp[n]['field1']
else:
the_list_tmp[n] = i
return the_list_tmp
the_list = recursiveChange(the_list)
print(the_list)
**OR**
the_list = [['www.url1.com)', 1429, [{'id': 1, 'field1': None},
{'id': 2, 'field1': None}], 'www.url2.com'], ['www.url1.com)', 1429,
[{'id': 3, 'field1': None}, {'id': 4, 'field1': None}]]]
df = pd.DataFrame(the_list[0][2]).rename(columns={'id': 'V1', 'field1': 'A'})
print(df)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.