pandas将长度不同的list或Series合并成一个dataframe

不同长度的Series和DataFrame合并

# s1为一个DataFrame,s2为一个Series
def expand_columns(s1, s2):
	s1.np.array(s1).tolist()
	data = [(k, ','.join(v)) for k in s2 for v in s1]
	data = pd.DataFrame(data, columns=[s2.name, 's1_tmp_name')
	data_expand = data['s1_tmp_name'].str.split(',', expand=True)
	data = pd.concat([data, data_expand], axis=1)
	data.drop(['s1_tmp_name'], inplace=True)
	data.columns = ('col1', 'col2', 'col3')
	return data
	

不同长度的list合并

ntest = ['a','b']
ltest = [[1,2], [4,5,6]]

data = [(k, v) for k, l in zip(ntest, ltest) for v in l]

print pd.DataFrame(data)

你可能感兴趣的:(pandas)