选择要在具有不同列数的文件循环中合并哪些列

时间:2018-11-05 09:34:51

标签: python pandas

我有字典:

Option Explicit

Sub Test()

    Dim cell As Range

    For Each cell In Worksheets("Sheet1").UsedRange '<= Search all usedrange cell by cell
        If cell.DisplayFormat.Interior.Color = RGB(192, 0, 0) Then
            Debug.Print cell.Address '<= if the cell has the color mentioned above will print it is address
        End If
    Next cell

End Sub

首先,如何使字典以某种方式将以 one列级联开头的值与保留在最终数据帧中所需的列分开的方式保持不变。

每个文件的列名称都不相同,因此很难自动执行此类自定义过程。你觉得呢?

我想对每个文件在新列中进行上述列的串联。 这应该是自动化的。

#file1 mentions 2 columns while file2 mentions 3
dict2 = ({'file1' : ['colA', 'colB'],'file2' : ['colY','colS','colX'], etc..})

我如何每次都可以独立于每本词典中的列数进行这项工作?

示例:

for k, v in dict1.items():
    df = pd.DataFrame.from_records(data=arcpy.da.SearchCursor(k, v)) #reads to a df
    df['new'] = df.astype(str).apply(' '.join, axis=1)#concatenation

结果:

file1

a = {'colA' : [123,124,112,165],'colB' :['alpha','beta','gamma','delta']}
file1 = pd.DataFrame(data = a)
file1

colA   colB
123    alpha
124    beta
112    gamma
165    delta

b = {'colY' : [123,124,112,165],'colS' :['alpha','beta','gamma','delta'], 'colX' :[323,326,378,399] }
file2 = pd.DataFrame(data = b)
file2

colY  colS      colX 
123   alpha     323
124   beta      326
112   gamma     378
165   delta     399

file2

col_all
123 alpha
124 beta
112 gamma
165 delta

注意

例如,

call_all 123 alpha 323 124 beta 326 112 gamma 378 165 delta 399 可以再增加5列,但只有3列应连接到一个列。如何使将定义要串联的列以及在那里仅存在的列的初始命令不受影响。

1 个答案:

答案 0 :(得分:1)

因此您必须为concat选择列名称,例如,按位置选择的前3列:

for k, v in dict1.items():
    df = pd.DataFrame.from_records(data=arcpy.da.SearchCursor(k, v)) #reads to a df
    df['new'] = df.iloc[:, :3].astype(str).apply(' '.join, axis=1)#concatenation

如果创建可能的列名列表,请使用intersection

for k, v in dict1.items():
    df = pd.DataFrame.from_records(data=arcpy.da.SearchCursor(k, v)) #reads to a df
    L = ['colA','colB','colS']
    cols = df.columns.intersection(L)
    df['new'] = df[cols].astype(str).apply(' '.join, axis=1)#concatenation

或过滤:

for k, v in dict1.items():
    df = pd.DataFrame.from_records(data=arcpy.da.SearchCursor(k, v)) #reads to a df
    L = ['colA','colB','colS']
    mask = df.columns.isin(L)
    df['new'] = df.loc[:, mask].astype(str).apply(' '.join, axis=1)#concatenation

编辑:

如果要使用其他必要列名称列表创建另一个数据结构,则可能的解决方案是创建元组列表:

L = [('file1', ['colA', 'colB'], ['colA','colB']), 
     ('file2', ['colY','colS','colX'], ['colY','colS'])]

for i, j, k in L:
    print (i)
    print (j)
    print (k)

file1
['colA', 'colB']
['colA', 'colB']
file2
['colY', 'colS', 'colX']
['colY', 'colS']

因此,您的解决方案应重写:

for i, j, k in L:
   df = pd.DataFrame.from_records(data=arcpy.da.SearchCursor(i, j)) #reads to a df
    df['new'] = df[k].astype(str).apply(' '.join, axis=1)#concatenation