对数据帧的行进行Tuplize

2024-04-24 04:58:13 发布

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

我有一个dataframetdf。它有几个列,其中三个是X,Y,Z

我想收集每一行,把X,Y,Z的值作为一个元组传递给一个函数。你知道吗

一开始我试过:

def format_tuple(x):
   print(x)
   return x

tmdf = tdf[['X', 'Y', 'Z']].applymap(format_tuple)

但是,这段代码将每个列“X”、“Y”、“Z”单独处理,如print(x)中所示,单独打印每个列的值,而不是将三列转换为一行tuple。你知道吗

然后我想,把这些值变成这样的tuple,但它不起作用:

tmdf = tdf[['X', 'Y', 'Z']].apply(tuple, axis=1).applymap(format_tuple)

Tags: 函数代码formatreturndef元组applyprint
1条回答
网友
1楼 · 发布于 2024-04-24 04:58:13

applymap用于元素转换。根据您的需求,沿第一个轴使用apply

def format_tuple(x):
   print(tuple(x.tolist()))
   return x

np.random.seed(0)
df = pd.DataFrame(np.random.randint(1, 100, (5, 3)), columns=list('XYZ'))
df

    X   Y   Z
0  45  48  65
1  68  68  10
2  84  22  37
3  88  71  89
4  89  13  59

df[['X', 'Y', 'Z']].apply(format_tuple, axis=1)
(45, 48, 65)
(45, 48, 65)
(68, 68, 10)
(84, 22, 37)
(88, 71, 89)
(89, 13, 59)

注意the first group is duplicated for performance reasons。你知道吗

相关问题 更多 >