我有一个数据帧,其中parameters
列是JSON,并且包含多个实际行和列:
input_data = pandas.DataFrame({'id':['0001','0002','0003'],
'parameters':["{'product':['book','cat','fish'],'person':['me','you']}",
"'{'product':['book','cat'],'person':['me','you','us']}'",
"'{'product':['apple','snake','rabbit','octopus'],'person':['them','you','us','we','they']}'"]})
...,我想从中提取以下数据帧:
product_data = pandas.DataFrame({'id':['0001','0001','0001','0002','0002','0003','0003','0003','0003'],
'product':['book','cat','fish','book','cat','apple','snake','rabbit','octopus']})
person_data = pandas.DataFrame({'id':['0001','0001','0002','0002','0002','0003','0003','0003','0003','0003'],
'person':['me','you','me','you','us','them','you','us','we','they']})
下面是我如何利用正则表达式将我带到那里。我怀疑这是最好的方法,但是就可以了:
for i in input_data.id.tolist():
s = ''.join(input_data[input_data.id == i]['parameters'])
product_string = re.search(r"product':(.*?),'person", str(s)).group(1)
product_data = pandas.DataFrame(product_string[1:-1].split(','))
person_string = re.search(r"person':(.*?)}", str(s)).group(1)
person_data = pandas.DataFrame(person_string[1:-1].split(','))
print("........")
print(product_data)
print("........")
print(person_data)
我想学习一种更快,更优雅或有益于健康的解决方案,该方案可能会捕获意想不到的细微差别。
答案 0 :(得分:2)
首先,使用str.get
访问器设置您的产品和人员
input_data['products'] = input_data.parameters.str.get('product')
现在,对于熊猫>= 0.25.0
,您可以使用explode
方法
input_data.explode('products')
对于大熊猫<= 0.25.0
,您可以参考to this thread
我假设您的数据帧中有字典,而不像这里公开的那样是 strings 。
如果您有字符串,可以总是
import ast
input_data.parameters.apply(ast.literal_eval)
使它们成为真正的词典。
答案 1 :(得分:0)
鉴于第2行和第3行中字符串的怪异结构,下面所需的最终输出是一种版本:
input_data = pd.DataFrame({'id':['0001','0002','0003'],
'parameters':["{'product':['book','cat','fish'],'person':['me','you']}",
"'{'product':['book','cat'],'person':['me','you','us']}'",
"'{'product':['apple','snake','rabbit','octopus'],'person':['them','you','us','we','they']}'"]})
input_data['parameters'] = input_data['parameters'].str.replace("'{", '{').str.replace("'{", '{').str.replace("}'", '}')
input_data = input_data.join(pd.DataFrame(input_data['parameters'].apply(literal_eval).values.tolist()))
products_len = input_data['product'].apply(len).values
persons_len = input_data['person'].apply(len).values
df
## flatten x into a list of dictionaries
values = input_data['person'].values.flatten().tolist()
flat_results = [item for sublist in values for item in sublist]
## reinsert a and b
person_df = pd.DataFrame(flat_results, columns = ['person'])
## flatten x into a list of dictionaries
values = input_data['product'].values.flatten().tolist()
flat_results = [item for sublist in values for item in sublist]
## reinsert a and b
product_df = pd.DataFrame(flat_results, columns = ['product'])
## person
ids = input_data['id'].repeat(persons_len).reset_index(drop=True)
person_df = person_df.join(ids)
## product
ids = input_data['id'].repeat(products_len).reset_index(drop=True)
product_df = product_df.join(ids)
person_df
Out[57]:
person id
0 me 0001
1 you 0001
2 me 0002
3 you 0002
4 us 0002
5 them 0003
6 you 0003
7 us 0003
8 we 0003
9 they 0003
product_df
Out[58]:
product id
0 book 0001
1 cat 0001
2 fish 0001
3 book 0002
4 cat 0002
5 apple 0003
6 snake 0003
7 rabbit 0003
8 octopus 0003