【问题标题】:create column by append the column from the different dataframe in pandas通过从熊猫中的不同数据框中附加列来创建列
【发布时间】:2019-11-25 21:41:48
【问题描述】:

我有一个数据框列表,我想在其中循环所有数据框并通过使用提供的列表过滤列来附加列来创建数据框。下面是代码

#df_ls contains list of dataframes 
df_ls = [A, B, C, D]
for j in df_ls:
    match_ls = ['card', 'brave', 'wellness']
    for i in text:
        if i in j.columns:
            print(i)
        df1 = j[i]
        df2 = df1
        df_full = df2.append(df1)

需要单列的 Result 新数据框包含所有 match_ls 字符串值。

A 
card  banner
rex   23 
fex   45
jex   66

B
brave laminate
max   ste
vax   pre
jox   lex

expected output
rex
fex
jex
max
vax
jox

【问题讨论】:

    标签: python pandas append concat


    【解决方案1】:

    将列表推导与Index.intersection 过滤列名称一起使用,最后使用concat 进行连接:

    df_ls = [A, B, C, D]
    match_ls = ['card', 'brave', 'wellness']
    dfs = [j[j.columns.intersection(match_ls)].stack().reset_index(drop=True) for j in df_ls]
    df_full = pd.concat(dfs, ignore_index=True)
    

    循环版本:

    dfs = []
    for j in df_ls:
        df = j[j.columns.intersection(match_ls)].stack().reset_index(drop=True) 
        print (df)
        dfs.append(df)
    
    df_full = pd.concat(dfs, ignore_index=True)
    print (df_full)
    

    【讨论】:

    • 嗨,Jezrael,我需要 match_ls 下的所有值在一个列中,而不是在单独的列中
    • @Vijayaraghavan 您应该创建一个带有预期输出的小示例,以使问题更加清晰。
    猜你喜欢
    • 1970-01-01
    • 2013-11-18
    • 2020-09-25
    • 1970-01-01
    • 1970-01-01
    • 2015-07-02
    • 2019-05-01
    • 1970-01-01
    • 2013-11-03
    相关资源
    最近更新 更多