Skip to main content
 首页 » 编程设计

python之Pandas 用 loc 打印出行

2024年10月01日8mengfanrong

我有一个 dataframe,在使用 print(df.T) 转置后打印出:

index_label    Col1    Col2    Col3    ....  # Goes on for 25 columns 
date_value1     v1      v1     v1      ....  # Max of 5 rows 
date_value2     v2      v2     v2      .... 
date_value3     v3      v3     v3      .... 
date_value4     v4      v4     v4      .... 
date_value5     v5      v5     v5      .... 

我尝试了以下代码来检索我感兴趣的行:

if my_date == 'date_value1': 
    print(df.T.loc[my_date]) 

这给出了结果:

index_label 
Col1        v1 
Col2        v1 
Col3        v1 
.... 
Name: date_value1, dtype: object 

我的问题是;如何让它以相同的格式打印出来,但只是我想要的 date_value?即:

index_label    Col1    Col2    Col3    .... 
date_value1     v1      v1     v1      .... 

请您参考如下方法:

看来你需要添加 [] 来返回 DataFrame 然后可能转置:

if my_date == 'date_value1': 
    print(df.T.loc[[my_date]]) 

或者:

if (my_date == 'date_value1'): 
    print(df[[my_date]].T) 

示例:

print (df) 
index_label date_value1 date_value2 date_value3 date_value4 date_value5 
Col1                 v1          v2          v3          v4          v5 
Col2                 v1          v2          v3          v4          v5 
Col3                 v1          v2          v3          v4          v5 
 
my_date = 'date_value1' 
if (my_date == 'date_value1'): 
    print(df[[my_date]].T) 
 
            Col1 Col2 Col3 
index_label                
date_value1   v1   v1   v1 

谢谢你更好的解释,piRSquared :

df.loc[stuff] the brackets here belong to loc and stuff is what it will get. If stuff is a scalar, you get a pd.Series. If stuff is a list or array then you get a pd.DataFrame.