1 回答
TA贡献1735条经验 获得超5个赞
输入 - 定义数据帧
import pandas as pd
df1 = pd.DataFrame({'A': [10,13,16], 'B': [11,14,17], 'C':[12,15,18]} )
df1.index = ['a_0','a_1','a_2']
df2 = pd.DataFrame({'start_column': [0,1,0], 'end_column': [1,2,2]} )
df2.index = ['a_0','a_1','a_2']
数据框输入:
A B C
a_0 10 11 12
a_1 13 14 15
a_2 16 17 18
start_column end_column
a_0 0 1
a_1 1 2
a_2 0 2
解决方案:
def listofdict(j):
d2 = {}
x = j['start_column']
y = j['end_column']+1
for i in range(x,y):
d1 = {}
d1['value'] = str(df1.loc[j.name][i])
d2[df1.columns[i]] = d1
l.append(d2)
return l
l = []
df2.apply(lambda j:listofdict(j), axis=1).all()
print(l)
期望的输出:
[{'A': {'value': '10'}, 'B': {'value': '11'}}, {'B': {'value': '14'}, 'C': {'value': '15'}}, {'A': {'value': '16'}, 'B': {'value': '17'}, 'C': {'value': '18'}}]
添加回答
举报