我有一個資料框:
id s1 s2 t1 t2
id1 4 7 9 6
id2 6 7 2 3
id3 2 2 7 2
id4 5 9 2 7
id5 6 1 5 1
我想為每個 id 行列印其中包含“1”的列對,然后列印其中包含“2”的列對(它們在值之前和之后,因此例如對于 id1,我會比較之前和之后的串列):
所以輸出應該是:
id1 = [4,9]
id2 = [6,2]
id3 = [2,7]
id4 = [5,2]
id5 = [6,5]
和 ts 一樣
id1 = [7,6]
id2 = [7,3]
id3 = [2,2]
id4 = [9,7]
id5 = [1,1]
然后我將比較每個 id list 的 s 和 t 值。
我寫:
for idx,row in df.iterrows():
id = row['id']
before_row = row.loc[:,row.column.str.contains('1')]
print(before_row)
#then get the after row by doing the same with contains('2')
#then compare the pair of lists
我得到了錯誤:
AttributeError: 'Series' object has no attribute 'column'
我理解列名不在串列中的錯誤,但不知道如何修復它;有人應該怎么做?
uj5u.com熱心網友回復:
不要使用iterrows,它很慢。您可以使用filter獲取以 1/2 結尾的列,然后如果確實需要,您可以應用回圈:
# asuming id is the index, else run
#df = df.set_index('id')
df1 = df.filter(regex='1$')
df2 = df.filter(regex='2$')
for idx, row in df1.iterrows():
print(row.to_list())
輸出:
[4, 9]
[6, 2]
[2, 7]
[5, 2]
[6, 5]
全自動拆分的另一種方法:
groups = df.columns.str.extract('(\d $)', expand=False)
dfs = dict(list(df.groupby(groups, axis=1)))
dfs['1']
s1 t1
id
id1 4 9
id2 6 2
id3 2 7
id4 5 2
id5 6 5
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/456657.html
上一篇:Pandaspivot_table-like輸出,垂直連接組中的多個列值
下一篇:使用累積計數器前向填充缺失的列
