Pandas:将数据框中的单行转换为具有多个维度的列表

2024-10-01 13:45:04 发布

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

为简单起见,我有两个数据帧,如下所示:

Df1
name year1 year2 year3
Eric 2019  2002  2008
Lana 2014  2018  2019

Df2
name year1 year2 year3
Sam  2017  2008  2003
Mary 2011  2010  2009

其中“name”是每个的索引

我只希望每个数据帧的最后一行提供如下输出,例如:

last_row_of_df = [[Lana], [2014], [2018], [2019]]

因为,如果我遍历数据帧,我可以附加一个名为“all_last_rows”的新列表,如下所示:

all_list_rows = [[[Lana], [2014], [2018], [2019]] , [[Mary], [2011], [2010], [2009]]]

作为回报,给我一个新的数据框,看起来像这样。但是我该怎么做呢

name year1 year2 year3
Lana 2014  2018  2019
Mary 2011  2010  2009

我真的很感激你的帮助

注意:我不能改变的是,我肯定会有几个数据帧,而且我肯定会执行一次迭代来遍历所有单独的数据帧 要生成一个新的数据帧,它将如下所示

the html output for the new data frame 是否有方法自动更正表中实际显示为int或NaN而不是[int]或[NaN]的值。因为在表格的底部,我想进行计算


Tags: the数据namenanallrowsintlast
3条回答

做:

last_row_of_df = [Df1.index[-1]] + list(Df1.iloc[-1,:])
last_row_of_df = [[item] for item in last_row_of_df]

使用:

df = pd.concat([x.iloc[[-1]] for x in [Df1, Df2]], ignore_index=True)

或:

df = pd.concat([x.tail(1) for x in [Df1, Df2]], ignore_index=True)

编辑:

out = []
for df in dfs:
    #some code
    out.append(df.iloc[[-1]])

df = pd.concat(out, ignore_index=True)
last_row_of_df = list(my_data.iloc[-1, :])
last_row_of_df = [item for item in last_row_of_df]

是什么让它看起来像预期的那样。虽然没有一个值是整数,但这很烦人

相关问题 更多 >