gpt4 book ai didi

python - Pandas 用 loc 打印出行

转载 作者:太空宇宙 更新时间:2023-11-04 02:51:51 25 4
gpt4 key购买 nike

我有一个 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.

关于python - Pandas 用 loc 打印出行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43614196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com