简体   繁体   English

从python中的pandas Series和DataFrames获取字符串?

[英]getting string from pandas Series and DataFrames in python?

I have this dataframe in pandas:我在熊猫中有这个数据框:

d=pandas.DataFrame([{"a": 1, "b": 1}, {"c": 2, "b": 4}])
d["name"] = ["Hello", "World"]

I want to select an element based on its string value in "name" column and then get the value as a string.我想根据“名称”列中的字符串值选择一个元素,然后将值作为字符串获取。 To select the element:要选择元素:

d[d["name"] == "World"]["name"]
Out:
1    World
Name: name

The problem is that it doesn't give a simple string but a series.问题是它没有给出一个简单的字符串,而是一个系列。 Casting to a string won't help -- how can I just get the string "World" out of this?转换为字符串无济于事——我怎样才能从中得到字符串"World" Is this the only way?这是唯一的方法吗?

d[d["name"] == "World"]["name"].values[0]

thanks.?谢谢。?

There's one method that no one mentioned that might be worth noting.有一种没有人提到的方法可能值得注意。 This was a problem I was having where I was doing multiple criteria checks and getting back a single item Series (basically a unique row result).这是我在进行多项标准检查并取回单个项目系列(基本上是唯一的行结果)时遇到的问题。 If you have a single item in a Series and just need that item OR know the index of the particular item you want to gather, just do this:如果您在系列中有一个项目并且只需要该项目或知道您要收集的特定项目的索引,请执行以下操作:

d[d["name"] == "World"].tolist()[0]

for the first (and only) item in a single item Series.对于单个项目系列中的第一个(也是唯一一个)项目。

Or this:或这个:

d[d["name"] == "World"].tolist()[index]

where index is the index of the item you are looking for in the Series.其中index是您在系列中查找的项目的索引。

If you want it as a string, you may have to cast as a string if it is not already stringified by default.如果您希望将其作为字符串,并且默认情况下尚未将其字符串化,则可能必须将其转换为字符串。

As @DSM points out, in general there could be many rows with name 'World' , so somewhere down the line we'll need to pick one.正如@DSM 指出的那样,通常可能有很多行名为'World' ,所以我们需要在某处选择一个。

One way to do this which seems kind of nice could be to use where (and then max ):一种看起来不错的方法是使用where (然后是max ):

In [11]: d.name.where(d.name == 'World', np.nan)
Out[11]: 
0      NaN
1    World
Name: name, dtype: object

In [12]: d.name.where(d.name == 'World', np.nan).max()
Out[12]: 'World'

Note: if there is no row with name 'World' this will return NaN.注意:如果没有名称为“World”的行,这将返回 NaN。

UPDATE: Not recommended as it truncates long text unless using pandas > 1.0 (not tested)更新:不推荐,因为它会截断长文本,除非使用 pandas > 1.0(未测试)

Not sure what versions of Pandas this works in, but its one other option:不确定这适用于哪些版本的 Pandas,但它是另一种选择:

d[d["name"] == "World"].to_string(index=False)

and if more than one row there are other options:如果不止一行,还有其他选项:

 max_rows      int, optional

Maximum number of rows to show before truncating.截断前显示的最大行数。 If None, show all.如果没有,则显示全部。

 min_rows      int, optional

The number of rows to display in a truncated repr (when number of rows is above max_rows).在截断的 repr 中显示的行数(当行数高于 max_rows 时)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM