我有巨大的数据框,看起来像这样:
Col1 Col2
0. 'w1'. 'N/A'
1. 'w2' 4.3
2. 'w3'. 1.2
4. 'w4'. 3.5
5. 'w5' 'N/A'
6. 'w6'. 3.1
7. 'w7'. 2.4
8. 'w8'. 1.7
9. 'w9'. 4.6
10. 'w10'. 'N/A'
11. 'w11'. 3.0
我在第一列中有字符串。在第二列中,我在某些行中有浮点数和“N/A”字符串。col1 中的字符串是问题的答案选项,col2 中的浮点数是答案平均值。计数和“N/A”字符串是问题本身。我的意图是在此数据框中创建另一个名为“Question_number”的列,其级别(Q1、Q2、Q3 ...)每次在 col2 中出现新的“N/A”行时都会发生变化。因此,我想要的输出是:
Col1 Col2 Col3
0. 'Q1' 'w1'. 'N/A'
1. 'Q1' 'w2' 4.3
2. 'Q1' 'w3'. 1.2
4. 'Q1' 'w4'. 3.5
5. 'Q2' 'w5' 'N/A'
6. 'Q2' 'w6'. 3.1
7. 'Q2'. 'w7'. 2.4
8. 'Q2' 'w8'. 1.7
9. 'Q3' 'w9'. 'N/A'
10. 'Q3' 'w10'. 2.0
11. 'Q3' 'w11'. 3.0
谁能帮我这个?我试过这个:
df['question_number']=np.where(df['counts']=='N/A', "Q1", "Q2", 'Q3')
但这不起作用,我不知道如何做到这一点。有人可以帮忙吗?
更新:@enke 的评论比我的代码干净得多。如果要将新列放在第一个位置,只需先添加该列。
# insert new column in first position
df.insert(0,'new','')
# Line from @enke's comment
df['new'] = 'Q'+df['Col2'].eq('N/A').cumsum().astype(str)
我的原帖在下面,如果你愿意,你可以忽略!
我在第一列位置插入了一个新列,然后循环遍历每一行。我重命名列名只是因为我可以。:DI 没有在您的原始 df 中包含引号和句点。但是下面的代码可能仍然有用。
import pandas as pd
cols = ['Answer', 'Avg_Score']
data=[['w1', 'N/A'],
['w2', 4.3],
['w3', 1.2],
['w4', 3.5],
['w5', 'N/A'],
['w6', 3.1],
['w7', 2.4],
['w8', 1.7],
['w9', 4.6],
['w10', 'N/A'],
['w11', 3.0]]
df = pd.DataFrame(data, columns = cols)
# insert new column before the Answer and the Avg_Score
df.insert(0,'Question','')
# start the question counter at 0
qnum = 0
# loop through each row
for index,row in df.iterrows():
# if 'N/A' found increase the question counter
# this assume first row will always have an 'N/A'
if df.loc[index,'Avg_Score'] == 'N/A':
qnum += 1
df.loc[index,'Question'] = 'Q{}'.format(qnum)
print(df)
输出:
Question Answer Avg_Score
0 Q1 w1 N/A
1 Q1 w2 4.3
2 Q1 w3 1.2
3 Q1 w4 3.5
4 Q2 w5 N/A
5 Q2 w6 3.1
6 Q2 w7 2.4
7 Q2 w8 1.7
8 Q2 w9 4.6
9 Q3 w10 N/A
10 Q3 w11 3.0
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句