【问题标题】:Extract values from a list and put them into a dataframe in Python从列表中提取值并将它们放入 Python 中的数据框中
【发布时间】:2021-10-17 20:00:23
【问题描述】:

我在列表中有数据(数字、数字)。 我想从此数据中减去尾随数字并将其放入数据框中。 列表中逗号前的数字等于数据框的索引。

--------------下面是一个代码示例。 -------------

import pandas as pd

test_list=[(1,124),(2,234),(3,344)]
test_data={
    'index' : [1,2,3],
    'data1' : [3,5,6],
    'data2' : [2,5,6]
}


test_df  =pd.DataFrame(test_data)
test_df

示例图片

我想将 test_list 添加到 test_df 的最后一列。 作为一个例子,我用一些例子制作了一个小列表和数据框。 可以这样说吗?

【问题讨论】:

    标签: python pandas list dataframe


    【解决方案1】:

    您可以从test_list 创建一个数据框,并将其合并到test_df

    >>> test_df.merge(pd.DataFrame(test_list, columns=['index', 'number']))
    
       index  data1  data2  number
    0      1      3      2     124
    1      2      5      5     234
    2      3      6      6     344
    

    另一种选择是使用字典而不是元组列表,然后使用pandas.Series.map 映射值:

    >>> test_d = {1: 124, 2: 234, 3: 344}
    >>> test_df['number']=test_df['index'].map(test_d)
    >>> test_df
       index  data1  data2  number
    0      1      3      2     124
    1      2      5      5     234
    2      3      6      6     344
    

    【讨论】:

      猜你喜欢
      • 2022-11-03
      • 1970-01-01
      • 2011-11-13
      • 2017-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多