【问题标题】:Python: is there a way to a Pandas Series object directly without using a listPython:有没有办法直接使用 Pandas 系列对象而不使用列表
【发布时间】:2020-11-01 23:18:05
【问题描述】:

我的目标是根据一组用户定义的输入创建一个新的 Pandas Series 对象。我目前正在使用以下代码执行此任务:

new_list = []
for _ in range(int(input("Enter number of entries: "))):
    new_list.append(input("Enter an element for the list: "))

new_series = pd.Series(new_list)
print(new_series)

工作正常。但是,我想知道是否有一种方法可以创建 new_series Series 对象而不附加和传递 new_list

【问题讨论】:

    标签: python pandas list data-structures series


    【解决方案1】:

    IIUC,像这样?

    new_series = pd.Series(dtype='int')
    for i in range(int(input("Enter number of entries: "))):
        new_series.loc[i] = input("Enter an element for the list: ")
    
    print(new_series)
    

    输出:

    Enter number of entries: 3
    Enter an element for the list: 1
    Enter an element for the list: 2
    Enter an element for the list: 3
    0    1
    1    2
    2    3
    dtype: object
    

    【讨论】:

      【解决方案2】:

      编辑 - 我想我更喜欢其他答案,但这里作为.append 的示例留下了

      您可以直接附加到系列对象:

      s = pd.Series()
      for _ in range(int(input("Enter number of entries: "))):
          s.append(pd.Series(input("Enter an element for the list: ")))
      print(s)
      

      例如:

      In [14]: s = pd.Series()
      
      In [15]: for _ in range(int(input('entries : '))):
          ...:     s = s.append(pd.Series(input('el : ')))
          ...:
      entries : 5
      el : 3
      el : 2
      el : 1
      el : 6
      el : 7
      
      In [16]: s
      Out[16]:
      0    3
      0    2
      0    1
      0    6
      0    7
      dtype: object
      
      

      【讨论】:

        猜你喜欢
        • 2017-03-23
        • 2013-08-08
        • 2021-03-30
        • 2021-10-09
        • 2021-11-22
        • 2019-02-27
        • 2020-03-14
        • 1970-01-01
        • 2013-12-19
        相关资源
        最近更新 更多