用新的数据框替换行 [英] Replace a row by a new Dataframe
本文介绍了用新的数据框替换行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找一种更优雅的方法来从字典的值替换另一个数据帧中的数据帧.
I am looking for a more elegant way to replace a dataframe in another dataframe from the values of a dictionary.
这是我必须使用的数据类型的示例
here its an example of the type of data i have to use
d = {1 : {'name' : 'bob','age' : 22,'Data' : {}},
4 : {'name' : 'sam','age' : 30,'Data' : {}},
2 : {'name' : 'tom','age' : 20,'Data' : [{'Mail':'B','MailValue': 89},
{'Mail':'C','MailValue' : 100}]},
3 : {'name' : 'mat','age' : 19,'Data' : [{'Mail':'D','MailValue': 71}]}} '
df = pd.DataFrame(d).T
df
Data age name
1 {} 22 bob
4 {} 30 sam
2 [{'Mail': 'B', 'MailValue': 89}, {'Mail': 'C',... 20 tom
3 [{'Mail': 'D', 'MailValue': 71}] 19 mat
这是我对最终单元格df2中的数据单元格的附加值以及复制名称和年龄列的实际解决方案
here is my actual solution for append value of Data cell and replicate name and age columns in the final dataframe df2
df2 = pd.DataFrame()
for idx, row in df[:].iterrows():
dfx = pd.DataFrame(row.Data)
dfx['idx'] = idx
df2 = df2.append(dfx)
df2.set_index('idx', inplace= True)
df2[df.columns] = df
df2 = df2.append(df.drop(df2.index.unique())).drop(columns = ['Data'])
print(df2)
Mail MailValue age name
2 B 89.0 20 tom
2 C 100.0 20 tom
3 D 71.0 19 mat
1 NaN NaN 22 bob
4 NaN NaN 30 sam
推荐答案
一种方法是将pd.concat
与可迭代的拆分数据帧一起使用,注意为空字典构造单行数据帧:
One way is to use pd.concat
with an iterable of split dataframes, taking care to construct a one-row dataframe for empty dictionaries:
splits = [pd.DataFrame(x if x else [{}]) for x in df.pop('Data')]
lens = list(map(len, splits))
df = pd.DataFrame({'age': np.repeat(df['age'].values, lens),
'name': np.repeat(df['name'].values, lens)})\
.join(pd.concat(splits, ignore_index=True))
print(df)
# age name Mail MailValue
# 0 22 bob NaN NaN
# 1 20 tom B 89.0
# 2 20 tom C 100.0
# 3 19 mat D 71.0
# 4 30 sam NaN NaN
这篇关于用新的数据框替换行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文