使用用户输入panda向数据帧添加列



如何在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")

你就快到了!已将追加更改为.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")

是否尝试此代码?

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)

您可以使用:

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。您可以根据自己的喜好更改此初始化值。将显示一条消息,其中也成功添加了列名。

相关内容

  • 没有找到相关文章

最新更新