簡體   English   中英

如何根據條件將級別添加到 pandas dataframe 中的新列?

[英]how to add levels to a new column in pandas dataframe based on a condition?

我有一個巨大的數據框,看起來像這樣:

     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”行時都會發生變化。 因此,我想要的 output 是:

     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 的評論比我的代碼干凈多了。 如果要將新列放在第一個 position 中,只需先添加該列即可。

Update2:在這篇關於添加 answer_option 列的帖子下方,根據您的問題添加更多代碼:

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 answer column in first so it's before the Answer and the Avg_Score
df.insert(0,'answer_option','')
# insert new question number column in the first position
df.insert(0,'question_number','')
# Line from @enke's comment
df['question_number'] = 'Q' + df['Avg_Score'].eq('N/A').cumsum().astype(str)
df['answer_option'] = 'A' + df.groupby('question_number').cumcount().add(1).astype(str)

print(df)

新 Output:

   question_number answer_option Answer Avg_Score
0               Q1            A1     w1       N/A
1               Q1            A2     w2       4.3
2               Q1            A3     w3       1.2
3               Q1            A4     w4       3.5
4               Q2            A1     w5       N/A
5               Q2            A2     w6       3.1
6               Q2            A3     w7       2.4
7               Q2            A4     w8       1.7
8               Q2            A5     w9       4.6
9               Q3            A1    w10       N/A
10              Q3            A2    w11       3.0

下面是我的原帖,想看的可以無視

我在第一列 position 中插入了一個新列,然后遍歷每一行。 我重命名列名只是因為我可以。 :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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM