【问题标题】:adding a column to a dataframe using user input pandas使用用户输入 pandas 向数据框添加列
【发布时间】:2021-05-18 09:10:21
【问题描述】:

如何在 pandas(python) 中使用用户输入添加列。如何修改代码来实现这一点?

sel= str(input("would you like to add a new column to df"))
if sel == "yes":
   name=str(input("Name of new column to df"))
   name=[]
   df= df.append(name)
else:
    print("column not added")

【问题讨论】:

  • 如果需要对解决方案进行进一步说明,请告知我们。如果没有其他问题,请选择您认为最适合您要求的解决方案。谢谢!

标签: python pandas dataframe data-science user-input


【解决方案1】:

你快到了!将附加更改为 .loc。见下文。

df = pd.DataFrame({1: [1, 2, 3], 2: [1, 2, 3]})
sel= str(input("would you like to add a new column to df"))
if sel == "yes":
    name=str(input("Name of new column to df"))
df.loc[:, name] = 'test values'
else:
    print("column not added")

【讨论】:

    【解决方案2】:

    试试这个代码?

    import pandas as pd
    x=[[1,2,3,4],[5,6,7,8],[9,10,11,12]]
    column_name=["Column 1","Column 2","Column 3"]
    d=input("Would you like to add columns to your dataframe? ")
    if d.lower()=="yes":
        new_columns=[]
        c=input("Add any four numbers to your dataframe, add a ',' after each number: ")
        name=input("Name you column: ")
        list1=str(c).split(",")
        for number in list1:
            number=int(number)
            new_columns.append(number)
        column_name.append(name)
        x.append(new_columns)
        df=pd.DataFrame(x,columns=column_name)
        print(df)
    else:
        print("No new columns were added.")
        column_name.append("Column 4")
        df=pd.DataFrame(x,columns=column_name)
        print(df)
    
    

    【讨论】:

      【解决方案3】:

      你可以使用:

      import numpy as np
      
      sel= str(input("would you like to add a new column to df"))
      if sel == "yes":
         name=str(input("Name of new column to df"))
         if name != '':
             df[name] = np.nan     # init to NaN.  You are freely to change this
             print(f"column {name} succesffuly added")
         else:
             print("Name empty. Column not added")
      else:
          print("column not added")
      

      这将检查列的输入名称是否为空字符串。如果为空,则不会添加列。如果列名不为空,则列内容将被初始化为NaN。您可以将此初始化值更改为您的偏好。将显示一条消息,其中列名也已成功添加。

      【讨论】:

        猜你喜欢
        • 2018-06-13
        • 2018-08-04
        • 1970-01-01
        • 2016-08-06
        • 1970-01-01
        • 2015-05-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多