2016-11-06 33 views
0

在Python,如何將字符串轉換等的Python:轉換串[( 'A',0.2),( 'B',0.9),( 'A',0.4)]到數據幀

thisStr = '[('a', 0.332), ('d', 0.43766), ('b', 0.3244), ('b', 0.76577), ('a', 0.863), ('d', 0.96789)]' 

成數據幀像

index item  value 
0  a  0.332 
1  d  0.43766 
2  b  0.3244 
3  b  0.76577 
4  a  0.863 
5  d  0.96789 
+1

這是一個元組列表... – Li357

+0

您的文字ABD,它在其他地方定義爲另一個字符串VAR或者它應該是「一個''b'和'd',例如。 ('a',0.332)? – Skycc

+0

感謝您的意見,我做了一個更新,使其更清楚我想要做什麼 –

回答

1

這聽起來像你正在尋找改變的字符串轉換成數據幀的大熊貓,然後做一些操作。通過對字符串的開頭和結尾的簡單替換和手動編輯,我將字符串更改爲以下內容。除了結尾之外,您正在轉義標點符號,以便您可以應用eval()函數。

import pandas as pd 

thisStr = eval('[(\'a\', 0.332), (\'d\', 0.43766), (\'b\', 0.3244), (\'b\', 0.76577), (\'a\', 0.863), (\'d\', 0.96789)]') 

df = pd.DataFrame(thisStr) 
df.rename(columns={0:'item', 1:'value'}, inplace=True) 

# one approach to solving the problem of removing rows where 
# item a has values less than 0.8. 
mask = (df['item'] == 'a') & (df['value'] < 0.8) 
df2 = df[~mask] 
1

使用eval函數把串入的元組的列表

# change to double quote " because contains single quote within string 
thisStr = "[('a', 0.332), ('d', 0.43766), ('b', 0.3244), ('b', 0.76577), ('a', 0.863), ('d', 0.96789)]" 

# this turn the string into list of tuples 
mylist = eval(thisStr) 
# mylist[0][0] access 1st row item which is 'a' 
# mylist[0][1] access 1st row value which is 0.332 

# to remove all row 'a' less than 0.8 
newlist = [i for i in mylist if not (i[0]=='a' and i[1] < 0.8)] 
相關問題