如何动态连接Pandas Dataframe列?

时间:2017-10-15 03:12:39

标签: python python-2.7 python-3.x pandas

我有一个数据帧df(参见下面的程序),其列名和数字不固定。 但是,有一个列表ls将具有需要附加在一起的df列的列表。 我试过了

df['combined'] = df[ls].apply(lambda x: '{}{}{}'.format(x[0], x[1], x[2]), axis=1)

但是在这里我假设列表ls有3个元素是硬编码和不正确的。如果列表有10个元素那么...我想动态读取列表并附加数据帧的列。

import pandas as pd

def main():
    df = pd.DataFrame({
        'col_1': [0, 1, 2, 3],
        'col_2': [4, 5, 6, 7],
        'col_3': [14, 15, 16, 19],
        'col_4': [22, 23, 24, 25],
        'col_5': [30, 31, 32, 33],
    })

    ls = ['col_1','col_4', 'col_3']
    df['combined'] = df[ls].apply(lambda x: '{}{}'.format(x[0], x[1]), axis=1)
    print(df)

    if __name__ == '__main__':
         main()

2 个答案:

答案 0 :(得分:3)

转换列后,您可以使用''.join'数据类型为 str

df[ls].astype(str).apply(''.join, axis=1)

#0    02214
#1    12315
#2    22416
#3    32519
#dtype: object

答案 1 :(得分:0)

为了更快的速度,您可以对字符串使用累积和,即

df[ls].astype(str).cumsum(1).iloc[:,-1].values

输出:

0    02214
1    12315
2    22416
3    32519
Name: combined, dtype: object

如果您需要添加空格,请先添加' ',然后找到总和,即

n = (df[ls].astype(str)+ ' ').sum(1)
0    0 22 14 
1    1 23 15 
2    2 24 16 
3    3 25 19 
dtype: object

时间:

ndf = pd.concat([df]*10000)

%%timeit
ndf[ls].astype(str).cumsum(1).iloc[:,-1].values
1 loop, best of 3: 538 ms per loop

%%timeit
ndf[ls].astype(str).apply(''.join, axis=1)
1 loop, best of 3: 1.93 s per loop
相关问题