如何将“ Python Pandas”列中的“ 2 + 3”之类的值转换为其汇总值 [英] How to convert values like '2+3' in a Python Pandas column to its aggregated value
问题描述
我在DataFrame中有一列名为致命性的列,其值很少像下面这样:
data [''fatalities'] = [1、4、10、1+ 8、5、2 + 9,,16、4 + 5]
I have a column in a DataFrame named fatalities in which few of the values are like below:
data[''fatalities']= [1, 4, , 10, 1+8, 5, 2+9, , 16, 4+5]
我想要类似'的值1 + 8','2 + 9'等
转换为汇总值,即
data [''fatalities'] = [1,4 、、、 10、9、5、11、16、9]
I want the values of like '1+8', '2+9', etc
to be converted to its aggregated value i.e,
data[''fatalities']= [1, 4, , 10, 9, 5, 11, , 16, 9]
我不确定如何编写代码来为Python中pandas DataFrame的专栏之一。但是,当我尝试使用以下代码时,它会引发错误。
I not sure how to write a code to perform above aggregation for one of the column in pandas DataFrame in Python. But when I tried with the below code its throwing an error.
def addition(col):
col= col.split('+')
col= int(col[0]) + int(col[1])
return col
data['fatalities']= [addition(row) for row in data['fatalities']]
错误:
IndexError: list index out of range
推荐答案
使用 pandas.eval
不同于纯python 评估:
data['fatalities'] = pd.eval(data['fatalities'])
print (data)
fatalities
0 1
1 4
2 10
3 9
4 5
5 11
6 16
7 9
但是因为此操作仅对 100
行有效,因为错误:
But because this working only to 100
rows because bug:
AttributeError:'PandasExprVisitor'对象没有属性'visit_Ellipsis'
AttributeError: 'PandasExprVisitor' object has no attribute 'visit_Ellipsis'
然后解决方案是:
data['fatalities'] = data['fatalities'].apply(pd.eval)
这篇关于如何将“ Python Pandas”列中的“ 2 + 3”之类的值转换为其汇总值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!