我有一个数据框列表,我想在其中循环所有数据框,并通过使用提供的列表过滤列来 append 列来创建数据框。下面是代码
#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)
需要单列的结果新数据框包含所有 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
最佳答案
使用列表理解并通过 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)
关于python - 通过追加 pandas 中不同数据帧的列来创建列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57069353/