pandas 如何从没有数据类型的 DataFrame 打印字符串值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28907321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:01:20  来源:igfitidea点击:

How to print string value from DataFrame without datatype

pythonpandas

提问by desmond

When I display a cell from a dataframe, I get

当我从数据框中显示一个单元格时,我得到

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

However, when I want to convert it to string, I get

但是,当我想将其转换为字符串时,我得到

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

How do I just print the value without dtypeand the name without string manipulations?

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

回答by EdChum

Just do the following, what is returned is a pandas Series so you need to acess either the valuesor the nameattribute:

只需执行以下操作,返回的是一个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'