python - 格式化 python pandas dataframe iterrows() 的行输出

标签 python pandas data-science

我有一个 python pandas 数据框 (my_df)。我想使用 iterrows() 提取行,然后将行转换为列表,最后将行转换列表附加到列表列表 (my_list )。

import pandas as pd

# DATA 
data = {'a': [8, 8, 8, 7],
    'b': [7, 8, 8, 8],
    'c': [7, 7, 8, 8],
    'd': [7, 7, 7, 7]
    }
my_df = pd.DataFrame(data, columns = ['a', 'b', 'c', 'd'])

print(my_df)
   a  b  c  d
0  8  7  7  7
1  8  8  7  7
2  8  8  8  7
3  7  8  8  7

问题是我从 iterrows() 中的 row 获取的格式,因为除了我想要的裸数据之外,它还包含其他信息。如何去除附加信息,以便获得所需的输出(请参阅下面的代码)?

谢谢!

# CODE 
my_list = []
for index, row in my_df.iterrows():
    my_list.append([row])


# OUTPUT
print(my_list)
[[a    8
b    7
c    7
d    7
Name: 0, dtype: int64], [a    8
b    8
c    7
d    7
Name: 1, dtype: int64], [a    8
b    8
c    8
d    7
Name: 2, dtype: int64], [a    7
b    8
c    8
d    7
Name: 3, dtype: int64]]


# DESIRE OUTPUT 
[[8, 7, 7, 7], [8, 8, 7, 7], [8, 8, 8, 7], [7, 8, 8, 7]]

最佳答案

只需使用tolist:

my_list = []
for index, row in my_df.iterrows():
    my_list.append(row.tolist())
print(my_list)

输出:

[[8, 7, 7, 7], [8, 8, 7, 7], [8, 8, 8, 7], [7, 8, 8, 7]]

关于python - 格式化 python pandas dataframe iterrows() 的行输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69014545/

相关文章:

Python子进程通信,顶部显示CPU使用率低

javascript - 在树莓派上的 HTML 和 python 之间发送消息

python-3.x - 匹配语句 "NaN"

python - 试图将四阶回归多项式拟合到散点图,但我得到了一个奇怪的结果

python - 如何处理空 'DataFrame' : no numeric data to plot error to take string on the graphs

machine-learning - 无论聚类中心如何初始化,Kmeans 算法都能保证收敛吗?为什么?

python - 理解 Python 中的初始化

Python 脚本只在 Docker 中产生僵尸进程

python - 如何删除数据框列的标题

python - 搜索 pandas.Series 中不存在的标签时出现 KeyError