【问题标题】:How to generate an array of paired tuples from a dataframe in python?如何从python中的数据帧生成成对元组数组?
【发布时间】:2021-04-21 14:12:32
【问题描述】:

我有一个包含两列的数据框,其中一列包含发送者,另一列包含接收者,示例如下:

https://i.stack.imgur.com/QsT38.png

我正在尝试将其转换为包含成对元组的数组,例如 [(1,141),(1,125),...,(149,29)],而无需手动输入每一对。如果这是一个常规数组,我知道如何自动添加元素,但我不知道如何为元组添加元素。

【问题讨论】:

    标签: python arrays pandas dataframe tuples


    【解决方案1】:

    回答你的问题有点棘手,因为我没有足够的元素(你的数据框只有 2 列吗?)

    如果是,答案如下:

    import pandas as pd
    
    # Create a dataframe
    d = {'col1': [1, 2], 'col2': [3, 4]}
    df = pd.DataFrame(data=d)
    
    # use to records to convert dataframe to a record np.array
    records = df.to_records(index=False)
    # convert to list
    result = list(records)
    print(result)
    

    只有当你有一个两列数据框时,它才会给你想要的结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-16
      • 2020-01-05
      • 1970-01-01
      • 2021-12-12
      • 1970-01-01
      • 1970-01-01
      • 2021-09-26
      • 1970-01-01
      相关资源
      最近更新 更多