[英]TypeError: list indices must be integers or slices, not str
#read from csv top and bottom
def get_interval(row):
return df[(df['DEPTH']>=row['top']) & (df['DEPTH']<=row['bottom'])]
#Combine all intervals
intervals = list(perf.apply(get_interval, axis=1))
pd.concat(intervals)
#summ al values in kh column in my data frame
x = intervals['kh'].sum()
I got:我有:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-22-d3a755411e27> in <module>
1 #Displaying and Summ the kh over the selected interval
2
----> 3 x = intervals['kh'].sum()
4
5 #print('\033[93m' + '\033[4m'+ '\033[1m' + 'Total kh =' + '\033[0m', GHZL_13 )
TypeError: list indices must be integers or slices, not str
I was expecting a sum from one column (kh) in my data frame我期待数据框中一列 (kh) 的总和
I think you are just trying to get the sum of the kh column for the rows that satisfy:我认为您只是想获取满足以下条件的行的 kh 列的总和:
top <= DEPTH <= bottom
(maybe you've got these the wrong way round? but I will use this). top <= DEPTH <= bottom
(也许你弄错了?但我会用这个)。
You can do this in one line using .loc[]
to filter the dataframe on those rows, and the kh column, then use .sum()
to get the sum like this:您可以在一行中使用
.loc[]
过滤这些行上的 dataframe 和 kh 列,然后使用.sum()
获取总和,如下所示:
df.loc[(df['DEPTH']>=df['top']) & (df['DEPTH']<=df['bottom']), 'kh'].sum()
for example, if df is:例如,如果 df 是:
df = pd.DataFrame({'DEPTH':[10, 15, 13],
'top':[5, 7, 10],
'bottom':[20, 7, 15],
'kh' : [10, 23, 17]})
DEPTH top bottom kh
0 10 5 20 10
1 15 7 7 23
2 13 10 15 17
then the.loc[] filtering of the rows ( df.loc[(df['DEPTH']>=df['top']) & (df['DEPTH']<=df['bottom'])]
) gives:然后 .loc[] 过滤行(
df.loc[(df['DEPTH']>=df['top']) & (df['DEPTH']<=df['bottom'])]
)给出:
DEPTH top bottom kh
0 10 5 20 10
2 13 10 15 17
You can then specify the kh column, and use.sum() (as described above) to get the sum of the kh column in the filtered df, which is 27 in this case.然后,您可以指定 kh 列,并使用 .sum()(如上所述)来获取过滤后的 df 中 kh 列的总和,在本例中为 27。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.