猿问

自动连接任意数量的列?

我有一本字典:


#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['first_col'].astype(str) + df['second_col'] etc.. #concatenation

我怎样才能每次都使这项工作独立于每个字典中的列数?


简单地连接所有提到的列。


更新


例子:


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


墨色风雨
浏览 112回答 2
2回答

偶然的你

使用时只需pd.concat()用axis=1:import pandas as pda = {'colA' : [123,124,112,165],'colB' :['alpha','beta','gamma','delta']}b = {'colY' : [123,124,112,165],'colS' :['alpha','beta','gamma','delta'], 'colX' :[323,326,378,399] }df = pd.concat([pd.DataFrame(i) for i in [a,b]], axis=1)产量:   colA   colB  colY   colS  colX0   123  alpha   123  alpha   3231   124   beta   124   beta   3262   112  gamma   112  gamma   3783   165  delta   165  delta   399
随时随地看视频慕课网APP

相关分类

Python
我要回答