python - 如何从 Dataframe 列形成元组列表

标签 python python-3.x pandas list dataframe

我有以下 pandas 数据框 df,前几个条目是:

     Input      Output
0    hj1234        2
1    gu0998        5
2    iu5678        7
3    56h781        11

我需要将它转换为 2 个单独的列表元组,如下所示:

my_inputs = [
   (h, j, 1, 2, 3, 4), 
   (g, u, 0, 9, 9, 8), 
   (i, u, 5, 6, 7, 8), 
   (5, 6, h, 7, 8, 1)]'
my_outputs =[(2,),
             (5,),
             (7,),
             (11,)]

我曾在 excel 中使用连接函数尝试过此操作,但是该函数的最大长度限制为一行中可以连接的字符数。所以我想用 python 来做。请协助

最佳答案

如果您真的想要,可以使用 applymapzip 来完成。

a, b = map(list, zip(*df.applymap(lambda x: (x, )).values.tolist()))   
a = list(map(tuple, [a_[0] for a_ in a]))

a
# [('h', 'j', '1', '2', '3', '4'),
#  ('g', 'u', '0', '9', '9', '8'),
#  ('i', 'u', '5', '6', '7', '8'),
#  ('5', '6', 'h', '7', '8', '1')]     
b
# [(2,), (5,), (7,), (11,)]

另一种选择是单独处理每一列。

a = list(map(tuple, df['Input']))
b = [(x, ) for x in df['Output']]

a
# [('h', 'j', '1', '2', '3', '4'),
#  ('g', 'u', '0', '9', '9', '8'),
#  ('i', 'u', '5', '6', '7', '8'),
#  ('5', '6', 'h', '7', '8', '1')]   
b
# [(2,), (5,), (7,), (11,)]

关于python - 如何从 Dataframe 列形成元组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54249182/

相关文章:

python - Python 中列表理解的多个条件

python - 在 Pandas 系列中嵌入一个范围

python - 尝试遍历字符串中的字符时 Python 的行为

python - 为什么在使用 concurrent.futures.ProcessPoolExecuter() 进行多处理期间不止一次打印此消息?

python - 如何在%APPDATA%文件夹python中写入文件

python - 在 python 中实现 fprintf 的简单方法是什么?

python - 按行/列对标签进行排序

python - 无法检测带有 blob 的图像

python - 将数据框的值居中

Python:将可迭代的元组转换为可迭代的字符串