我试图从使用熊猫的数据框中选择三列[“ attacktype1”,“ attacktype2”,“ attacktype3”]的数据类型为整数,并想将那几列中的fillna(0)总计为新列。[ “总攻击”]

可以从以下位置下载数据集:
单击[此处] https://s3.amazonaws.com/datasetsgun/data/terror.csv

我尝试一次将fillna(0)应用于一列,然后将它们总计到一个新的单列中。

我的第一种方式:

da1 = pd.read_csv('terror.csv', sep = ',', header=0 , encoding='latin' , na_values=['Missing', ' '])
da1.head()
#Handling missing values
da1['attacktype3'] = da1['attacktype3'].fillna(0)
da1['attacktype2'] = da1['attacktype2'].fillna(0)
da1['attacktype1'] = da1['attacktype1'].fillna(0)
da1['total_attacks'] = da1['attacktype3'] + da1['attacktype2'] + da1['attacktype1']

#country_txt is a column which consists of different countries.Want to find "Total_atacks" only for India. Therefore, the condition applied is country_txt=='India'.

a1 = da1.query("country_txt=='India'").agg({'total_attacks':np.sum})
print(a1)


我的第二种方式(不起作用):

da1 = pd.read_csv('terror.csv', sep = ',', header=0 , encoding='latin' , na_values=['Missing', ' '])
da1.head()
#Handling missing values
check1=Df.country_txt=="India"
store=Df[["attacktype1","attacktype2","attacktype3"]].apply(lambda x:x.fillna(0))

Total_attack=Df.loc[check1,store].sum(axis=1)
print(Total_attack)





I want to apply fillna(0) to multiple columns in a single line and also total those columns in an alternate and effective way.

The error that I get when I use my second way is:

ValueError: Cannot index with multidimensional key

最佳答案

首先用boolean indexingDataFrame.loc过滤,然后用DataFrame.fillna替换缺少的值:

check1 = Df.country_txt == "India"
cols = ["attacktype1","attacktype2","attacktype3"]

Df['Total_attack'] = Df.loc[check1, cols].fillna(0).sum(axis=1)


对于标量,一个数字输出加sum

Total_attack = Df['Total_attack'].sum()
print (Total_attack)
35065.0

关于python - 使用pandas选择多个列和fillna()的另一种方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56205958/

10-09 18:55