gpt4 book ai didi

python - 如何将用户输入的值附加到 df 的不同列中?

转载 作者:太空宇宙 更新时间:2023-11-04 11:11:54 25 4
gpt4 key购买 nike

我正在尝试根据用户输入创建一个 df,如下所示:

import pandas as pd
data = pd.DataFrame(columns=['ID','QTY', 'MOA', 'TAX'])

while True:
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 ')

data['ID'].append(int(id_value))
data['QTY'].append(int(qty_value))
data['MOA'].append(int(moa_value))
data['TAX'].append(int(tax_value))

else:
break

每当用户想要输入段时,他选择Y 并开始输入值。现在,我也想将这些值添加到 df 中。我尝试附加它,但它给了我以下错误:

Traceback (most recent call last):

File "", line 13, in data['ID'].append(int(id_value))

File "C:\Users\kashy\Anaconda3\envs\py36\lib\site-packages\pandas\core\series.py", line 2775, in append to_concat, ignore_index=ignore_index, verify_integrity=verify_integrity

File "C:\Users\kashy\Anaconda3\envs\py36\lib\site-packages\pandas\core\reshape\concat.py", line 255, in concat sort=sort,

File "C:\Users\kashy\Anaconda3\envs\py36\lib\site-packages\pandas\core\reshape\concat.py", line 332, in init raise TypeError(msg)

TypeError: cannot concatenate object of type ''; only Series and DataFrame objs are valid

示例:

Do you want to add a segment (Y/N)?: y

ID 66

QTY 654

MOA 6565

TAX 6

Do you want to add a segment (Y/N)?: y

ID 656

QTY 61

MOA 65

TAX 64651

根据这些值,df 必须按如下方式形成:

ID    QTY    MOA    TAX
66 654 6565 6
656 61 65 64651

如何做到这一点?

最佳答案

您可以创建字典并使用DataFrame.append :

import pandas as pd
data = pd.DataFrame(columns=['ID','QTY', 'MOA', 'TAX'])

while True:
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:
break

print (data)

另一个想法是使用 python append 创建字典列表并最后调用 DataFrame 构造函数:

L = []
while True:
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)

关于python - 如何将用户输入的值附加到 df 的不同列中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58006759/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com