我有一个pandas dataFrame fruits ::
df = pd.read_csv(newfile, header=None)
df
0 1 2 3 4 5 6 7
0 Apple Bananas Fig Elderberry Cherry Honeydew NaN NaN
1 Bananas Cherry Dragon Elderberry NaN NaN NaN NaN
2 Cherry Grape NaN NaN NaN NaN NaN NaN
3 Dragon NaN Apple Bananas Cherry Elderberry NaN NaN
4 Elderberry Apple Bananas Fig Grape NaN NaN NaN
5 Fig Cherry Honeydew Apple NaN NaN NaN NaN
6 Grape NaN NaN NaN NaN NaN NaN NaN
7 Honeydew Grape Fig Elderberry Dragon Cherry Bananas Apple
我正试图找到“水果配对”,例如在第一排,Apple和Fig是一对,第6排是Fig和Apple。同样适用于Apple-Elderberry和Elderberry-Apple,但不包括Apple和Bananas(从Bananas开始没有苹果)。
我有以下代码正常工作,这就是这个::
fruits = df[0]
stock = df.drop(0, axis=1)
for i in range(len(fruits)):
string1 = str(fruits[i])
full_line = (stock.iloc[i])
line = np.array(full_line.dropna(axis=0))
if len(line) > 0 :
for j in range(len(stock)):
iind = (fruits[fruits == line[j]].index[0])
this_line = stock.iloc[iind]
logic_out = this_line.str.match(string1)
print(logic_out)
BUT !! (1)由于Pandas系列区分大小写而且(2)布尔输出是True,Falses和NaN的混合,它在fruit == line [j]处中断。理想情况下,我只想算真相。任何和所有的帮助v。非常感谢!!
答案 0 :(得分:1)
我将使用设置逻辑,pandas堆叠和numpy广播
f = lambda x: x.title() if isinstance(x, str) else x
s = df.applymap(f).set_index('0').rename_axis(None).stack().groupby(level=0).apply(set)
f = s.index
p = s.values
one_way = (p[:, None] & [{x} for x in f]).astype(bool)
[(f[i], f[j]) for i, j in zip(*np.where(one_way & one_way.T))]
[('Apple', 'Elderberry'),
('Apple', 'Fig'),
('Apple', 'Honeydew'),
('Bananas', 'Dragon'),
('Bananas', 'Elderberry'),
('Dragon', 'Bananas'),
('Elderberry', 'Apple'),
('Elderberry', 'Bananas'),
('Fig', 'Apple'),
('Fig', 'Honeydew'),
('Honeydew', 'Apple'),
('Honeydew', 'Fig')]