Python 将具有不同值的JSON提取到pandas中的重复id列
我有以下数据帧:Python 将具有不同值的JSON提取到pandas中的重复id列,python,json,pandas,concat,Python,Json,Pandas,Concat,我有以下数据帧: df = pd.DataFrame({'id':['0001', '0001'], 'vat_countries': [{'vat': 21, 'country': 'ES'}, {'vat': 23, 'country': 'GR'}] }) id vat_countries 0001 {'vat':
df = pd.DataFrame({'id':['0001', '0001'],
'vat_countries': [{'vat': 21, 'country': 'ES'},
{'vat': 23, 'country': 'GR'}]
})
id vat_countries
0001 {'vat': 21, 'country': 'ES'}
0001 {'vat': 23, 'country': 'GR'}
我想得到的是:
id vat country
0001 21 'ES'
0001 23 'GR'
通过阅读其他问题,我得到了以下代码:
df = df.drop('vat_countries', 1).assign(**pd.DataFrame(list_df['vat_countries'].values.tolist()))
然而,这给了我:
id vat country
0001 21 'ES'
0001 21 'ES'
这是错误的
我已经能够通过以下方式获得我想要的结果:
c = pd.concat([pd.DataFrame(df[column].values.tolist()),
df.drop(column, 1).reset_index()],
axis=1, ignore_index=True)
但这需要手动键入列名。否则,列名为0、1、2、3
在保留列名称的同时,是否有任何方法可以获得所需的输出?
谢谢
编辑:尝试BEN_YO解决方案。我有这个
代码之后我得到了这个
所有内容都会重复两次我会在带有
dict
s的列中应用pd.Series
,并将结果与原始结果连接,即:
import pandas as pd
df = pd.DataFrame({'id':['0001', '0001'], 'vat_countries': [{'vat': 21, 'country': 'ES'}, {'vat': 23, 'country': 'GR'}]})
final_df = df.join(df.vat_countries.apply(pd.Series))
print(final_df)
输出:
id vat_countries vat country
0 0001 {'vat': 21, 'country': 'ES'} 21 ES
1 0001 {'vat': 23, 'country': 'GR'} 23 GR
如您所见,增值税已被保留,如果您希望放弃增值税,您可以简单地放弃它。我将在dict
s列应用pd.Series
,并将结果与原始结果连接,即:
import pandas as pd
df = pd.DataFrame({'id':['0001', '0001'], 'vat_countries': [{'vat': 21, 'country': 'ES'}, {'vat': 23, 'country': 'GR'}]})
final_df = df.join(df.vat_countries.apply(pd.Series))
print(final_df)
输出:
id vat_countries vat country
0 0001 {'vat': 21, 'country': 'ES'} 21 ES
1 0001 {'vat': 23, 'country': 'GR'} 23 GR
如您所见,增值税已被保留,如果您希望放弃增值税,您可以简单地删除它。尝试pop
修复您的代码
df.join(pd.DataFrame(df.pop('vat_countries').tolist(),index=df.index))
Out[300]:
id vat country
0 0001 21 ES
1 0001 23 GR
尝试使用pop
修复代码
df.join(pd.DataFrame(df.pop('vat_countries').tolist(),index=df.index))
Out[300]:
id vat country
0 0001 21 ES
1 0001 23 GR
您可以使用字符串方法访问各个值
:
df["vat"] = df.vat_countries.str["vat"]
df["country"] = df.vat_countries.str["country"]
df
id vat_countries vat country
0 0001 {'vat': 21, 'country': 'ES'} 21 ES
1 0001 {'vat': 23, 'country': 'GR'} 23 GR
您可以使用字符串方法访问各个值
:
df["vat"] = df.vat_countries.str["vat"]
df["country"] = df.vat_countries.str["country"]
df
id vat_countries vat country
0 0001 {'vat': 21, 'country': 'ES'} 21 ES
1 0001 {'vat': 23, 'country': 'GR'} 23 GR
在我的真实例子中,所有的东西都被复制了。有关更多信息,请参见编辑的问题details@JavierLópezTomás我使用的是你的样本数据,如果这不适用于真实数据,请找出你的样本数据和真实数据之间的差异,并在你的问题中更新样本数据是的,我在我的样本数据中得到了它。我对问题进行了编辑,以展示一个示例。我将尝试用你的答案制作一个与真实数据错误相同的样本数据。同时,你能看一下这些表吗?@JavierLópezTomás df=df.reset_index(drop=True),然后运行上面的解决方案~在我的真实示例中,它让我看到了所有重复的内容。有关更多信息,请参见编辑的问题details@JavierLópezTomás我使用的是你的样本数据,如果这不适用于真实数据,请找出你的样本数据和真实数据之间的差异,并在你的问题中更新样本数据是的,我在我的样本数据中得到了它。我对问题进行了编辑,以展示一个示例。我将尝试用你的答案制作一个与真实数据错误相同的样本数据。同时,在运行上述解决方案之前,您是否可以看看这些表?@JavierLópezTomás df=df.reset_index(drop=True)~