我必须进行一项调查,然后将许多学生的答案保存在数据框中。我尝试将答案存储在列表中,但不起作用,因为当我尝试将答案保存在数据框中时,我得到的数据框在同一列中包含多个答案,而不是作为答案数量的许多行。 这是我的调查
sex=input('your sex: ')
sex_list.append(sex)
country=input('where do you come from?: ')
country_list.append(country)
sport=input('have you ever play sport?: ')
sport_list.append(sport)
if sport=='no':
reason_no_sport=input('why didnt you play sport?:')
reason_no_sport_list.append(reason_no_sport)
else:
reason_no_sport=np.nan
reason_no_sport_list.append(reason_no_sport)
football=input('have you ever play football?: ')
football_list.append(football)
basket=input('have you ever play basket?: ')
basket_list.append(basket)
swimming=input('have you ever play swimming?: ')
swimming_list.append(swimming)
这是列表
sex_list=[]
country_list=[]
sport_list=[]
reason_no_sport_list=[]
football_list=[]
basket_list=[]
swimming_list=[]
这是数据框
df = pd.DataFrame({"sex": [sex_list],
"country": [country_list],
"sport":[sport_list],
"why didnt you play sport?": [reason_no_sport_list],
"football":[football_list],
"basket":[basket_list],
"swimming":[swimming_list]})
这是结果,类似于
sex=`[male, female]`
country= `[usa, england]`
最佳答案
我为您的问题提供了一个可能的解决方案。我创建列表并在其中添加答案:
sex=[]
country=[]
sport=[]
reason_no_sport=[]
football=[]
basket=[]
swimming=[]
interview='doing'
while interview.upper()=='DOING':
if((input('Can you answer some questions?: ')).upper()=='YES'):
sex.append(input('your sex: '))
country.append(input('where do you come from?: '))
s=input('have you ever play sport?: ')
sport.append(s)
if s.upper() == 'NO':
reason_no_sport.append(input('why didnt you play sport?:'))
football.append(np.nan)
basket.append(np.nan)
swimming.append(np.nan)
else:
reason_no_sport.append(np.nan)
football.append(input('have you ever play football?: '))
basket.append(input('have you ever play basket?: '))
swimming.append(input('have you ever play swimming?: '))
if((input('Do you want to do another interview?: ')).upper()=='YES'):
continue
else:
break
df=pd.DataFrame()
df['sex']=sex
df['country']=country
df['sport']=sport
df['reason_no_sport']=reason_no_sport
df['football']=football
df['basket']=basket
df
Output example:
Can you answer some questions?: yes
your sex: m
where do you come from?: spain
have you ever play sport?: no
why didnt you play sport?:i don't like it
Do you want to do another interview?: yes
Can you answer some questions?: no
Do you want to do another interview?: yes
Can you answer some questions?: yes
your sex: f
where do you come from?: portugal
have you ever play sport?: yes
have you ever play football?: yes
have you ever play basket?: no
have you ever play swimming?: yes
Do you want to do another interview?: no
<小时/>
sex country sport reason_no_sport football basket swimming
0 m spain no i don't like it NaN NaN NaN
1 f portugal yes NaN yes no yes
您还可以创建一个列表(名称
)并询问名称并将其用作DataFrame
索引:
名称=[]
name.append(input('你叫什么名字:'))
df.reindex(名称)
关于python - 如何在Python数据框中存储调查的答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57692009/