[英]pandas.DataFrame: How to merge rows with a common column value in the same pandas.DataFrame
[英]How do I find the position of a value in a pandas.DataFrame?
我想在下面的 DataFrame 的索引中搜索“row3”,对于从零开始的数组,它应该是 2。
import numpy as np
import pandas as pd
rownames = ['row1', 'row2', 'row3', 'row4', 'row5']
colnames = ['col1', 'col2', 'col3', 'col4']
# Create a 5 row by 4 column array of integers from 0 to 19
integers = np.arange(20).reshape((5, 4))
table = pd.DataFrame(integers, index=rownames, columns=colnames)
是否有返回“row3”行号的函数? 在此先感谢您的帮助。
您可以使用Index.get_loc
( docs ):
>>> table.index.get_loc("row3")
2
>>> table.iloc[table.index.get_loc("row3")]
col1 8
col2 9
col3 10
col4 11
Name: row3, dtype: int64
>>> table.loc["row3"]
col1 8
col2 9
col3 10
col4 11
Name: row3, dtype: int64
但这是一种有点不寻常的访问模式——我自己从不需要它。
您可能只是找到从“row1”到“row3”的 df 长度并将其减少 1(如果您从 0 开始计数)。
s = 'row3'
print(s,'number is', len(table['row1':s]) - 1)
返回
row3 number is 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.