关于Dataframe.loc/.iloc和字符串操作的问题

2024-10-03 00:25:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Pandas数据帧,并尝试对特定单元格执行一些字符串操作。你知道吗

对于这个任务,我循环遍历dataframe,用.loc选择所需的单元格,将其分配给一个变量,并对这个变量执行字符串操作。你知道吗

 for i in range(0,len(df_single)):
        firmenname_cics = df_single.loc[i,'FIRMENNAME_CICS'].to_string() 
        firmenname_fb = df_single.loc[i,'FIRMENNAME_FB'].to_string()
        .. firmenname_fb.stringOperation ..

我的问题是,变量的类型是“Series Object”,所以在执行操作之前必须将其转换为字符串类型。我读doc,原因是(在我的示例中)i不是一个整数值,而是索引的标签。你知道吗

(Quote from Pandas Doc: A single label, e.g. 5 or 'a', (note that 5 is interpreted as a label of the index, and never as an integer position along the index).

所以转换“Series对象”并不是一个大问题,但我想知道,是否有办法以字符串格式提取单元格的值?(例如Excel VBA)

我还研究了.iloc,它为我做了整数位置的事情,但似乎不允许我访问所需的列。你知道吗


Tags: theto字符串类型pandasdfstringfb
1条回答
网友
1楼 · 发布于 2024-10-03 00:25:16

您可以使用iloc引用特定列:

>>> import pandas as pd
>>> mydict = [{'a': 1, 'b': 2, 'c': 3, 'd': 4}, {'a': 100, 'b': 200, 'c': 300, 'd': 400},{'a': 1000, 'b': 2000, 'c': 3000, 'd': 4000 }]
>>> df = pd.DataFrame(mydict)
>>> df
      a     b     c     d
0     1     2     3     4
1   100   200   300   400
2  1000  2000  3000  4000
>>> df.iloc[0]
a    1
b    2
c    3
d    4
Name: 0, dtype: int64
>>> df.iloc[0]["a"]
1

相关问题 更多 >