小编kha*_*oth的帖子

如何动态连接 Pandas Dataframe 列?

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

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

但在这里我假设列表 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()
Run Code Online (Sandbox Code Playgroud)

python python-2.7 python-3.x pandas

1
推荐指数
1
解决办法
3155
查看次数

标签 统计

pandas ×1

python ×1

python-2.7 ×1

python-3.x ×1