gpt4 book ai didi

python - 对 pandas DataFrame 的行进行元组化

转载 作者:太空宇宙 更新时间:2023-11-03 14:06:51 24 4
gpt4 key购买 nike

我有一个dataframe tdf。它有几列,其中三列是 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) 中所示,单独打印每列的值,而不是将三列转换为单行元组

然后我想,将值转换为像这样的元组,但它不起作用:

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

最佳答案

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 .

关于python - 对 pandas DataFrame 的行进行元组化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48819634/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com