[英]Create dataframe mapping a list of arrays
我有兩個數據框,一個帶有輸入信息,另一個帶有輸出:
df_input:
index col1 col2
0 'A' 'B'
1 'B' 'H'
2 'C' 'D'
df_output:
index vectors
0 [[D, 0.5],[E, 0.3]]
1 [[A, 0.3]]
2 [[B, 0.8],[C, 0.5],[H, 0.2]]
輸出是一個數組數組。 數量可變。
我需要的是映射索引並在行中附加每個向量,如下所示:
df:
index col1 col2 val1 val2
0 'A' 'B' 'D' 0.5
1 'A' 'B' 'E' 0.3
2 'B' 'H' 'A' 0.3
3 'C' 'D' 'B' 0.8
4 'C' 'D' 'C' 0.5
5 'C' 'D' 'H' 0.2
df非常大,因此我嘗試盡可能避免循環。
預先感謝您的估計。
哪里:
input_vectors = pd.DataFrame({'vectors':[[['D', .5],['E',.3]],
[['A',.3]],
[['B',.8],['C',.5],['H',.2]]]})
input_vectors
輸出:
vectors
0 [[D, 0.5], [E, 0.3]]
1 [[A, 0.3]]
2 [[B, 0.8], [C, 0.5], [H, 0.2]]
和
df_input
輸出:
index col1 col2
0 0 A B
1 1 B H
2 2 C D
采用:
pd.concat([pd.DataFrame(x, index=[i]*len(x))
for i, x in input_vectors.itertuples()])\
.join(df_input)
輸出:
0 1 index col1 col2
0 D 0.5 0 A B
0 E 0.3 0 A B
1 A 0.3 1 B H
2 B 0.8 2 C D
2 C 0.5 2 C D
2 H 0.2 2 C D
使用堆棧功能將列表列表分成幾行。 然后,對於vectors列中的每一行,將其轉換為字符串,並使用split函數創建兩列va1和va2。 使用concat通過索引列連接兩個數據框。 刪除列索引,因為在最終輸出中不需要該列索引。
import pandas as pd
my_dict = {'index':[0,1,2], 'col1':['A','B','C'], 'col2':['B','H','D']}
df_input = pd.DataFrame(my_dict)
my_dict = {'index':[0,1,2],'vectors':[[['D', 0.5],['E', 0.3]],[['A', 0.3]],[['B', 0.8],['C', 0.5],['H', 0.2]]]}
df_output = pd.DataFrame(my_dict)
df_output = df_output.vectors.apply(pd.Series).stack().rename('vectors')
df_output = df_output.to_frame().reset_index(1, drop=True).reset_index()
df_tmp = df_output.vectors.apply(lambda x: ','.join(map(str, x))).str.split(',', expand=True)
df_tmp.columns = ['va1','val2']
df_tmp = pd.concat([df_tmp, df_output['index']], axis=1, sort=False)
df_tmp = df_input.join(df_tmp.set_index('index'), on='index')
df_tmp.reset_index(drop=True).drop(columns=['index'])
結果:
col1 col2 va1 val2
0 A B D 0.5
1 A B E 0.3
2 B H A 0.3
3 C D B 0.8
4 C D C 0.5
5 C D H 0.2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.