通过从不同的数据帧中追加列来创建列

2024-06-16 10:05:22 发布

您现在位置:Python中文网/ 问答频道 /正文

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

#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)

需要结果新的dataframe与单列包含所有匹配的字符串值

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

Tags: 数据indfforcardlsmaxrex
1条回答
网友
1楼 · 发布于 2024-06-16 10:05:22

对按^{}筛选列名称使用列表理解,最后使用^{}连接在一起:

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)

相关问题 更多 >