如何将具有两个键的词典拆分为两个独立的新列?

2024-04-26 03:43:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Pandas,我有一个列,它有一个带两个键(a'11'和a'10')的字典。你知道吗

这就是我所拥有的

Id  (dictionary1, dictionary2)
0   {a'11': [a'255', a'258'], a'10': [a'224', a'222']}  
1   {a'11': [a'262', a'261'], a'10': [a'214', a'212']}  
2   {a'11': [a'241', a'238'], a'10': [a'244', a'202']}  

我需要将此列分为两个新列,一个具有a'10'值,另一个具有a'11'值。你知道吗

这样做的正确代码是什么?你知道吗


Tags: 代码idpandas字典dictionary2dictionary1
2条回答

DataFrame一起使用tolist

pd.DataFrame(df.d.tolist())
           10          11
0  [224, 222]  [255, 258]
1  [224, 222]  [255, 258]
2  [224, 222]  [255, 258]

可以使用str访问器对包含iterables的Series进行索引:

import pandas as pd

df = pd.DataFrame([[{'a': 1, 'b':2}], [{'a': 3, 'b': 4}]], columns=['d'])

print(df, '\n')
print(df['d'].str['a'])

输出:

                  d
0  {'a': 1, 'b': 2}
1  {'a': 3, 'b': 4} 

0    1
1    3

相关问题 更多 >