使用熊猫在多列中选择多列和fillna()的另一种方法

时间:2019-05-19 08:16:18

标签: python python-3.x pandas spyder valueerror

我正在尝试从三个使用熊猫的数据框中选择其数据类型为整数的三列[“ attacktype1”,“ attacktype2”,“ attacktype3”],并想将那几列填充为(0)并将这些列总计为一个新列列。[“ Total_attacks”]

可以从以下位置下载数据集: 点击[这里] 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

1 个答案:

答案 0 :(得分:1)

首先用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