简体   繁体   English

如何从pandas数据帧中提取单元格

[英]How to extract cell from pandas data frame

Say I make a pandas dataframe (I am not good at pandas , and this may not be very efficient): 假设我制作了一个pandas数据帧(我不擅长pandas ,这可能效率不高):

import pandas as pd
colnames = ['a', 'b']
data = pd.DataFrame(columns=colnames)
df_row = ['val1', 'val2']
app = pd.Series(df_row, index=cols)
data = data.append(app, ignore_index=True)

I want to access val1 as a string, not as a pandas object. 我想将val1作为字符串访问,而不是作为pandas对象访问。

If I do: 如果我做:

cell = data.iloc[[0],[0]]
type(cell)

I see that cell is of type <class 'pandas.core.frame.DataFrame'> 我看到该cell类型为<class 'pandas.core.frame.DataFrame'>

If I then do: 如果我那么做:

type(cell[`a'])

I see that it is <class 'pandas.core.series.Series'> 我看到它是<class 'pandas.core.series.Series'>

How can I get val1 as a str object and not a pandas object? 如何将val1作为str对象而不是pandas对象?

The issue for your case is that you are passing lists to iloc , you need to pass normal integers 0,0 to iloc to get the result you want - 您的案例的问题是您将列表传递给iloc ,您需要将正常的整数0,0传递给iloc以获得您想要的结果 -

In [85]: data.iloc[0,0]
Out[85]: 'val1'

要以字符串形式访问DataFrame中的值:

cell = str(data.iloc[0,0])

For integer based indexing a specific cell in a DataFrame (or Series), iat is generally the most efficient: 对于基于整数的索引DataFrame(或Series)中的特定单元格, iat通常是最有效的:

>>> data.iat[0, 0]
'val1'

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

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