2017-05-30 46 views
1

我有一列包含電話號碼(字符串)。然後有另一列給了我零的數量(如int),我想追加到現有的電話號碼。我想要做的是像(5 *「0」=>「00000」)。還有一個先決條件。如果電話號碼結束於「1」,則只能添加零。根據在另一列中設置的金額向零和列添加零點

Example: 
>>> df = pd.DataFrame([["11", 2], ["21", 3], ["10", 6]], columns=['phone', 'ext_length']) 

What I tried: 
>>> df.loc[(df.phone.str.endswith("1")), "complete_phone"] = df.phone + (df.ext_length * "0") 

同時過濾正確的行,其中的手機上「1」結尾,創造列「complete_phone」的作品,我不能得到的「數學」的工作。我越來越

TypeError: ufunc 'multiply' did not contain a loop with signature matching types dtype('<U21') dtype('<U21') dtype('<U21') 

我也不理解錯誤消息,況且我有一個想法,如何解決這個問題。我還在尋找一個鏈接,它顯示瞭如何正確包含Python示例,正如我在[in:]和[out:]加結果中看到的其他問題。任何提示?

回答

1

我認爲你需要mask的更換,如果條件Truestr.repeat:與DataFrame.apply

s = pd.Series(['0'], index=df.index) 
mask = df.phone.str.endswith("1") 
df["complete_phone"] = df.phone.mask(mask, df.phone + s.str.repeat(df.ext_length)) 
print (df) 
    phone ext_length complete_phone 
0 11   2   1100 
1 21   3   21000 
2 10   6    10 

另一種解決方案:

mask = df.phone.str.endswith("1") 
df["complete_phone"] = df['phone'].mask(mask, df.apply(lambda x: x['phone'] + 
                   '0' * x.ext_length, axis=1)) 
print (df) 
    phone ext_length complete_phone 
0 11   2   1100 
1 21   3   21000 
2 10   6    10 
mask = df.phone.str.endswith("1") 
df["complete_phone"] = df.phone.mask(mask, df['phone'] + 
              df['ext_length'].apply(lambda x:'0'*x)) 
print (df) 
    phone ext_length complete_phone 
0 11   2   1100 
1 21   3   21000 
2 10   6    10 

你的解決方案是類似的只得到NaN如果馬SK是False

mask = df.phone.str.endswith("1") 
df.loc[mask, "complete_phone"] = df['phone'] + df.apply(lambda x: '0' * x.ext_length, axis=1) 
    phone ext_length complete_phone 
0 11   2   1100 
1 21   3   21000 
2 10   6   NaN 
+0

謝謝,這幫助了很多。我還在搞清楚你到底在做什麼。但我可以馬上應用於我的實際問題。我正在使用str.repeat方法。 – SLglider

0
In [1]: import pandas as pd 

In [2]: df = pd.DataFrame([["11", 2], ["21", 3], ["10", 6]], columns=['phone', 'ext_length']) 

In [3]: df 
Out[3]: 
    phone ext_length 
0 11   2 
1 21   3 
2 10   6 

In [4]: df['complete_phone'] = [number+'0'*length if number.endswith('1') else number for number, length in zip(df.phone, df.ext_length)] 

In [5]: df 
Out[5]: 
    phone ext_length complete_phone 
0 11   2   1100 
1 21   3   21000 
2 10   6    10 
+0

有趣的方法,但我不完全明白它(還)。儘管如此,它可能會幫助我解決另一個問題。 – SLglider

+0

所以'In [4]:'@SLglider列表理解中的方法是壓縮兩列('phone'和'ext_length'),然後執行檢查,看看末尾是否有1。如果是這樣,請對該號碼進行所需的更改,如果不是,則保持不變。然後把這個結果放到'complete_phone'中,希望這有助於! :) –

0

我覺得apply功能就派上用場了:

df = pd.DataFrame([["11", 2], ["21", 3], ["10", 6]], columns=['phone', 'ext_length']) 
df['complete_phone'] = df.apply(lambda x: x['phone'] + "0" * x['ext_length'], axis=1)