圖片 我想在資料小于 10 時獲取列名。我可以使用 loc 或 iloc 獲取或連接到資料,但找不到獲取列名的函式或其他東西。
ex) 如果220609,MANGO = 7和220610,的日期Mango=2, 那么我需要這樣做;
if df.iloc[0,1:]<10==True:
然后我想得到 220609 和 220610
我不知道如何為此撰寫代碼以獲得每個專案的列名。
我應該怎么辦?謝謝!
uj5u.com熱心網友回復:
這是一般的想法。盡管通常注意不要迭代行,但在這種情況下,您必須這樣做,因為您的結果對于不同的行會有不同的長度。
import pandas as pd
data = [
[ 'APPLE', 10, 10,8, 5 ],
[ 'BANANA', 3,10, 2, 0 ],
[ 'KIWI', 10,4, 10,2 ],
[ 'MELON', 10, 10, 3, 10 ],
[ 'MANGO', 7, 2, 10, 10 ]
]
df = pd.DataFrame(data, columns=['FRUIT',220609,220610,220611,220612])
df.set_index('FRUIT',inplace=True)
print(df)
for fruit,row in df.iterrows():
print(fruit, df.columns[row<10])
輸出:
220609 220610 220611 220612
FRUIT
APPLE 10 10 8 5
BANANA 3 10 2 0
KIWI 10 4 10 2
MELON 10 10 3 10
MANGO 7 2 10 10
APPLE [220611, 220612]
BANANA [220609, 220611, 220612]
KIWI [220610, 220612]
MELON [220611]
MANGO [220609, 220610]
uj5u.com熱心網友回復:
此方法使用對列索引的索引。
使用您的示例
dfx.columns[1:][dfx.iloc[0,1:].lt(10)].to_list()
結果
['220611', '220612']
uj5u.com熱心網友回復:
您可以使用df.melt條件
df[df<10].melt(ignore_index=False).dropna().sort_values(by='FRUIT')
variable value
FRUIT
APPLE 220611 8.0
APPLE 220612 5.0
BANANA 220609 3.0
BANANA 220611 2.0
BANANA 220612 0.0
KIWI 220610 4.0
KIWI 220612 2.0
MANGO 220609 7.0
MANGO 220610 2.0
MELON 220611 3.0
之后,如果您想根據所需的水果選擇資料,您可以使用df.loc.
ddf.loc[["APPLE"]]["variable"].to_list()
[220611, 220612]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/496092.html
上一篇:填充NA并從另一個資料框中更新列
