2016-11-06 60 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)] 
相关问题