在Python中为列表分配值并转换数据

时间:2019-06-04 21:09:55

标签: python arrays list dataframe transform

我是Python的新手,正在努力进行一些基本的转换(喜欢!)

我想编写代码来打开具有ID和位置的excel工作簿,并通过将所说位置映射到代码的函数运行每一行(请注意,我不想一次全部合并行需要单独运行该功能):

Desired Results

到目前为止,我已经设法编写了以下代码:

import pandas as pd

ids = "IDs.xlsx"
df_IDs = pd.read_excel(ids)

codes = "MAP.xlsx"
df_codes = pd.read_excel(codes)

def prop_id(location):
    datapoints = [[location, "Yes"]]
    df = pd.DataFrame(datapoints, columns=['Location', 'Is Match'])
    merge = pd.merge(df_codes, df, how='left', left_on='Location', right_on='Location')
    fltr = merge.dropna()
    column = fltr[['Code']]
    output = column.values.tolist()
    return output

df_IDs['PlaceID'] = df_IDs['Location'].apply(prop_id)
print(df_IDs)

这将输出以下内容:

   ID    Property    Location          PlaceID
0  1234  Property A  Location 1  [[A], [E], [F]]
1  1235  Property B  Location 2            [[B]]

然后我要完成的工作是将ID列映射到PlaceID列中的每个列表值,并使数据垂直。换句话说:

   ID    Property    Location     PlaceID
0  1234  Property A  Location 1   A
1  1234  Property A  Location 1   E         
1  1234  Property A  Location 1   F
1  1235  Property B  Location 2   B 

任何帮助将不胜感激。谢谢!

0 个答案:

没有答案