我有一个这样的数据框,其中“组合”列看起来像[(-34,-58),(-3,-5)]。但我希望它转换为['-34,-58,-3,-5']。我该如何实现?

df = pd.DataFrame(
    {
     'X_1': [-34, -1, -33, 4, 10],
     'Y_1': [-58, -4, -70, -74, -66],
     'X_2': [-3, -1, -3, 4.0, 1],
     'Y_2': [-5, -4, -7, -7.8, -6]})

df['Coordinates_Top_right'] = list(zip(df.X_1, df.Y_1))
df['Coordinates_top_left'] = list(zip(df.X_2, df.Y_2))
df['combine'] = df[['Coordinates_Top_right','Coordinates_top_left']].apply(list,axis=1)

#Tried this but doesnt give me the desired output:

df['area'] = df[['Coordinates_Top_right','Coordinates_top_left']].apply(list,axis=1)

最佳答案

采用:

import itertools
df['combine'] = df[['Coordinates_Top_right','Coordinates_top_left']].\
                       apply(lambda x: list(itertools.chain(*x)),axis=1)
print(df)

   X_1  Y_1  X_2  Y_2 Coordinates_Top_right Coordinates_top_left  \
0  -34  -58 -3.0 -5.0            (-34, -58)         (-3.0, -5.0)
1   -1   -4 -1.0 -4.0              (-1, -4)         (-1.0, -4.0)
2  -33  -70 -3.0 -7.0            (-33, -70)         (-3.0, -7.0)
3    4  -74  4.0 -7.8              (4, -74)          (4.0, -7.8)
4   10  -66  1.0 -6.0             (10, -66)          (1.0, -6.0)

                  combine
0  [-34, -58, -3.0, -5.0]
1    [-1, -4, -1.0, -4.0]
2  [-33, -70, -3.0, -7.0]
3     [4, -74, 4.0, -7.8]
4    [10, -66, 1.0, -6.0]

关于python - 连接两列以进行自定义传递,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55147635/

10-12 19:44