2017-09-18 99 views
0

例如刪除所有字符指定字符後列中的數據幀。如何使用Python

import pandas as pd 
import numpy as np 
data = {'state': ['Auckland', 'Otago (....)','Wellington','Dunedin','Hamilton'],'year': [2000, 2001, 2002, 2001,2002],'pop': [1.5, 1.7,3.6, 2.4, 2.9]} 
df = pd.DataFrame(data) 

我想刪除該字符串之後發生的一切「(」在狀態欄

非常感謝您的幫助。

薩米爾

回答

0

我不知道很多關於大熊貓,但在谷歌小的搜索,我在這裏s表示可以處理你的處境代碼:

import pandas as pd 
import numpy as np 
data = {'state': ['Auckland', 'Otago (....)','Wellington','Dunedin','Hamilton'],'year': [2000, 2001, 2002, 2001,2002],'pop': [1.5, 1.7,3.6, 2.4, 2.9]} 
df = pd.DataFrame(data) 

for state in df.state: 
    if "(" in state: 
     row_num = df.loc[df['state']==state].index[0] 
     df.at[row_num, 'state'] = state[:state.index("(")] 

print(df.state) 

這裏是輸出:

0  Auckland 
1  Otago 
2 Wellington 
3  Dunedin 
4  Hamilton 
Name: state, dtype: object 
0

Series.map功能越過所有值在Series並返回另一個Series包含一些功能的結果。從那裏你可以在切片中使用str.find()方法。

import pandas as pd 

data = {'state': ['Auckland', 'Otago (....)','Wellington','Dunedin','Hamilton'],'year': [2000, 2001, 2002, 2001,2002],'pop': [1.5, 1.7,3.6, 2.4, 2.9]} 

df = pd.DataFrame(data) 

df['state'] = df.state.map(lambda x: x[0: x.find('(') - 1] if '(' in x else x) 

print(df) 

產量:

pop  state year 
0 1.5 Auckland 2000 
1 1.7  Otago 2001 
2 3.6 Wellington 2002 
3 2.4  Dunedin 2001 
4 2.9 Hamilton 2002