我想根据列和行的某些功能总结我选择的所有值。
另一种方法是我想使用行索引和列索引的函数来确定一个值是否应该包含在沿轴的和中。
有没有一种简单的方法可以做到这一点?
答案 0 :(得分:3)
可以使用语法dataframe[<list of columns>]
选择列。索引(行)可用于使用dataframe.index
方法进行过滤。
import pandas as pd
df = pd.DataFrame({'a': [0.1, 0.2], 'b': [0.2, 0.1]})
odd_a = df['a'][df.index % 2 == 1]
even_b = df['b'][df.index % 2 == 0]
# odd_a:
# 1 0.2
# Name: a, dtype: float64
# even_b:
# 0 0.2
# Name: b, dtype: float64
答案 1 :(得分:2)
如果df
是您的数据框:
In [477]: df
Out[477]:
A s2 B
0 1 5 5
1 2 3 5
2 4 5 5
您可以像这样访问奇数行:
In [478]: df.loc[1::2]
Out[478]:
A s2 B
1 2 3 5
和偶数的这样:
In [479]: df.loc[::2]
Out[479]:
A s2 B
0 1 5 5
2 4 5 5
要回答您的问题,请获取偶数行和列B
:
In [480]: df.loc[::2,'B']
Out[480]:
0 5
2 5
Name: B, dtype: int64
和奇数行和列A
可以完成:
In [481]: df.loc[1::2,'A']
Out[481]:
1 2
Name: A, dtype: int64
答案 2 :(得分:0)
我认为如果不是最干净的实施,这应该是相当普遍的。这应该允许根据条件(我在字典中定义)为行和列应用单独的函数。
import numpy as np
import pandas as pd
ran = np.random.randint(0,10,size=(5,5))
df = pd.DataFrame(ran,columns = ["a","b","c","d","e"])
# A dictionary to define what function is passed
d_col = {"high":["a","c","e"], "low":["b","d"]}
d_row = {"high":[1,2,3], "low":[0,4]}
# Generate list of Pandas boolean Series
i_col = [df[i].apply(lambda x: x>5) if i in d_col["high"] else df[i].apply(lambda x: x<5) for i in df.columns]
# Pass the series as a matrix
df = df[pd.concat(i_col,axis=1)]
# Now do this again for rows
i_row = [df.T[i].apply(lambda x: x>5) if i in d_row["high"] else df.T[i].apply(lambda x: x<5) for i in df.T.columns]
# Return back the DataFrame in original shape
df = df.T[pd.concat(i_row,axis=1)].T
# Perform the final operation such as sum on the returned DataFrame
print(df.sum().sum())