[英]How do I concatenate a list of pandas dataframes using python?
我有一个 function functionA
,它采用文件路径并输出 dataframe dfA
我有一个包含所有文件路径的列表listAll
我正在尝试创建一个 function functionB
,它接受listAll
并输出 1 个 dataframe dfB
,它是所有文件路径的dfA
的聚合
问题:我无法弄清楚聚合部分,我尝试的一切最终都会创建一个dfB
,它是 1 dataframe 但只包含重复的最后一个文件路径的dfA
(长度基于listAll
)
试过:
def functionB(listAll):
for i in range(len(listAll)):
Tables = functionA(listAll[i])
return Tables
Table1 = [functionB(listAll) for x in listAll]
dfB = pd.concat(Table1)
def functionB(listAll):
Tables = pd.DataFrame()
for i in range(len(listAll)):
Tables = pd.concat([functionA(listAll[i])]),axis=0,ignore_index=True)
return Tables
Table1 = [functionB(listAll) for x in listAll]
dfB = pd.concat(Table1)
在您的两次试验中,Tables 变量都被覆盖了!
尝试(我 pythonized;)):
def combine_dataframes(path_list: list[str]):
tables = pd.DataFrame()
for path in path_list:
# feel free to add axis/ignore_index:
tables.concat(functionA(path))
return tables
uberframe = combine_dataframes(listAll)
concat
还可以获取其他数据帧的列表。 我想这也应该有效:
def dataframe_from_paths(all_paths):
tables = pd.DataFrame()
return tables.concat([functionA(path) for path in all_paths])
最后使用 reduce:
from functools import reduce
def dataframe_from_paths(all_paths):
def concat_dataframes(a, b):
return a.concat(functionA(b))
return reduce(concat_dataframes, all_paths, pd.DataFrame())
reduce
采用 function,一个可迭代的和可选的起始元素。
function 包含魔法。 它需要 2 arguments,第一个是最后一个元素,第二个是当前元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.