还是报错AttributeError: 'DataFrame' object has no attribute 'tolist'
时间: 2023-08-15 18:05:45 浏览: 141
非常抱歉,我之前的回答有误。在 DataFrame 上使用 tolist()
方法是不正确的。
要从 DataFrame 中提取每一行的最小的前3个值和对应的索引,并将其导出到一个新的 DataFrame 中,您可以使用 apply()
方法结合 nsmallest()
函数来实现。以下是修改后的代码示例:
import pandas as pd
# 假设您的 DataFrame 名为 df
# 提取每一行的最小的前3个值和对应的索引
min_top3_df = df.apply(lambda row: row.nsmallest(3).reset_index(), axis=1)
# 创建一个新的 DataFrame
new_df = pd.DataFrame(columns=["Value_1", "Index_1", "Value_2", "Index_2", "Value_3", "Index_3"])
# 填充新的 DataFrame
for idx, row in min_top3_df.iteritems():
new_df.loc[idx] = row.values.flatten()
# 输出新的 DataFrame
print(new_df)
在上述代码中,df
是您的原始 DataFrame。通过 apply()
方法对每一行使用 nsmallest(3)
函数,以获取每行的最小的前3个值和对应的索引。使用 reset_index()
来重新设置索引。
然后,我们创建一个空的新 DataFrame,该新 DataFrame 将用于存储提取出的值和索引。我们指定新 DataFrame 的列名("Value_1", "Index_1", "Value_2", "Index_2", "Value_3", "Index_3")。
最后,我们使用 iteritems()
遍历 min_top3_df
,并通过 values.flatten()
将每一行的值展平为一维数组,并将其填充到新 DataFrame 中的相应行。
请注意,根据您的实际数据结构和需求,您可能需要适当地调整代码。
相关推荐


















