如何在没有数据类型的情况下从 DataFrame 打印字符串值

How to print string value from DataFrame without datatype

当我显示数据框中的单元格时,我得到

df[df.a==1]['b']
Out[120]: 
0    2
Name: b, dtype: int64

然而,当我想将其转换为字符串时,我得到

str(df[df.a==1]['b'])
Out[124]: '0    2\nName: b, dtype: int64'

如何只打印没有 dtype 的值和没有字符串操作的名称?

只需执行以下操作,返回的是 pandas 系列,因此您需要访问 valuesname 属性:

In [2]:

df = pd.DataFrame({'a':np.arange(5), 'b':np.random.randn(5)})
df
Out[2]:
   a         b
0  0 -1.795051
1  1  1.579010
2  2  1.908378
3  3  1.814691
4  4 -0.470358

In [16]:

type(df[df['a']==2]['b'])
Out[16]:
pandas.core.series.Series

In [9]:

df[df['a']==2]['b'].values[0]
Out[9]:
1.9083782154318822

In [15]:

df.loc[df['a']==2,'b'].name
Out[15]:
'b'