我有兩個資料框如下,
import pandas as pd
d1 ={'col1': ['I ate dinner','I ate dinner', 'the play was inetresting','the play was inetresting'],
'col2': ['min', 'max', 'mid','min'],
'col3': ['min', 'max', 'max','max']}
d2 ={'col1': ['I ate dinner',' the glass is shattered', 'the play was inetresting'],
'col2': ['min', 'max', 'max'],
'col3': ['max', 'min', 'mid']}
df1 = pd.DataFrame(d1)
df2 = pd.DataFrame(d2)
我在 df2 中創建了一個名為“exist”的列,并根據 df2.col1 中的句子是否存在于 df1.col1 中添加了值(真、假):
common = df1.merge(df2,on=['col1'])
index_list = df2[(~df2.col1.isin(common.col1))].index.to_list()
df2['exist'] = ' '
df2.loc[index_list, 'exist'] = 'false'
df2.loc[df2["exist"] == " ",'exist'] = 'true'
我現在想做的是,如果存在列中的值 == true,我想將該行添加到 df1 中的類似行下。所以期望的輸出應該是:
output:
col1 col2 col3
0 I ate dinner min min
1 I ate dinner max max
2 I ate dinner min max
3 the play was inetresting mid max
4 the play was inetresting min max
5 the play was inetresting max mid
我想我必須使用 np.where,但我不確定如何制定附加以獲得所需的輸出
uj5u.com熱心網友回復:
第一個想法是過濾df2值df1.col1并附加到df1byconcat然后按以下方式排序DataFrame.sort_values:
df = pd.concat([df1, df2[(df2.col1.isin(df1.col1))]]).sort_values('col1', ignore_index=True)
print (df)
col1 col2 col3
0 I ate dinner min min
1 I ate dinner max max
2 I ate dinner min max
3 the play was inetresting mid max
4 the play was inetresting min max
5 the play was inetresting max mid
如果只需要兩個 DataFrame 中的共同值,則可以通過以下方式過濾numpy.intersect1d:
common = np.intersect1d(df1['col1'], df2['col1'])
df = (pd.concat([df1[df1.col1.isin(common)],
df2[df2.col1.isin(common)]])
.sort_values('col1', ignore_index=True))
print (df)
uj5u.com熱心網友回復:
IIUC,您想要添加匹配的行而不一定依賴排序。
df2b = df2.set_index('col1')
(df1
.groupby('col1', as_index=False, group_keys=False)
.apply(lambda d: pd.concat([d, df2b.loc[[d.name]].reset_index()]))
.reset_index(drop=True)
)
輸出:
col1 col2 col3
0 I ate dinner min min
1 I ate dinner max max
2 I ate dinner min max
3 the play was inetresting mid max
4 the play was inetresting min max
5 the play was inetresting max mid
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/443997.html
上一篇:pyspark表到熊貓資料框
