在句子结构中显示数据框行

时间:2017-06-23 14:15:20

标签: python pandas

我有一个简单的pandas数据框,有3列:Num,Question,Answer:

Num        Question Answer
 1   What is your favorite color? Green
 2  Favorite sport? Basketball

基本上我只想在句子结构中呈现此数据帧的每一行,如下所示:

Question #1: What is your favorite color? Answer: Green
Question #2: Favorite sport? Answer: Basketball

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

您可以使用iterrows

df = pd.DataFrame({"Question": ['What is your favorite color?', 'Favorite sport?'],
                   "Answer": ['Green', 'Basketball'],
                   "Num": [1, 2]})

for _, row in df.iterrows():
    print("Question #{0}: {1} Answer: {2}".format(
        row['Num'], row['Question'], row['Answer']))

# Output:
# Question #1: What is your favorite color? Answer: Green
# Question #2: Favorite sport? Answer: Basketball