How To Append User Inputted Values Into Different Columns Of A Df?
I am trying to create a df based on the user inputs as follows: import pandas as pd data = pd.DataFrame(columns=['ID','QTY', 'MOA', 'TAX']) while True: add_seg = input('Do you
Solution 1:
You can crete dictionary and use DataFrame.append
:
import pandas as pd
data = pd.DataFrame(columns=['ID','QTY', 'MOA', 'TAX'])
whileTrue:
add_seg = input('Do you want to add a segment (Y/N)?: ')
if (add_seg == 'Y')|(add_seg == 'y'):
id_value = input('ID ')
qty_value = input('QTY ')
moa_value = input('MOA ')
tax_value = input('TAX ')
d = {'ID':int(id_value),'QTY':int(qty_value),'MOA':int(moa_value),'TAX':int(tax_value)}
data = data.append(d, ignore_index=True)
else:
breakprint (data)
Another idea is create list of dictionaries with python append
and last call DataFrame
constructor:
L = []
whileTrue:
add_seg = input('Do you want to add a segment (Y/N)?: ')
if (add_seg == 'Y')|(add_seg == 'y'):
id_value = input('ID ')
qty_value = input('QTY ')
moa_value = input('MOA ')
tax_value = input('TAX ')
d = {'ID':int(id_value),'QTY':int(qty_value),'MOA':int(moa_value),'TAX':int(tax_value)}
L.append(d)
else:
break
data = pd.DataFrame(L, columns=['ID','QTY', 'MOA', 'TAX'])
print (data)
Solution 2:
After the inputs use:
data.loc[len(data)] = [int(id_value), int(qty_value), int(moa_value), int(tax_value)]
Solution 3:
Alternatively, append empty row and then set its columns:
while True:
add_seg = input('Do you want to add a segment (Y/N)?: ')
if (add_seg == 'Y')|(add_seg == 'y'):
data = data.append({}, ignore_index=True)
last_row = data.iloc[-1];
for c indata.columns:
last_row[c] = int(input(c))
else:
break
Post a Comment for "How To Append User Inputted Values Into Different Columns Of A Df?"