df= pd.read_csv('portfolios.csv')
df1 = df.set_index('id');df
df1
大家好,我不确定如何开始。我在这里附了一张图片。请问如何定义用户函数,通过该函数输入ID,我将获得整行?
感谢您的帮助。问题:
答案 0 :(得分:2)
用于一行DataFrame
,将loc
与双[]
一起使用,对于Series
,仅一个[]
:
df = pd.DataFrame({'id':[1,2,3,4,5,6],
'B':[4,5,4,5,5,4],
'C':[7,8,9,4,2,3],
'D':[1,3,5,7,1,0],
'E':[5,3,6,9,2,4],
'F':list('aaabbb')})
df1 = df.set_index('id')
print (df1)
B C D E F
id
1 4 7 1 5 a
2 5 8 3 3 a
3 4 9 5 6 a
4 5 4 7 9 b
5 5 2 1 2 b
6 4 3 0 4 b
def get_line1(x, val):
row = x.loc[[val]]
return row
def get_line2(x, val):
row = x.loc[val]
return row
out = get_line1(df1, 5)
print (out)
B C D E F
id
5 5 2 1 2 b
out = get_line2(df1, 5)
print (out)
B 5
C 2
D 1
E 2
F b
Name: 5, dtype: object