Python 将特定值合并到一个特定的文件中
我目前正在合并Python 将特定值合并到一个特定的文件中,python,pandas,merge,Python,Pandas,Merge,我目前正在合并行中的第一个和最后一个字符串。这些字符串位于特定值右侧时合并。我希望将其更改为低于特定值 import pandas as pd d = ({ 'A' : ['X','Foo','','X','Big'], 'B' : ['No','','','No',''], 'C' : ['Merge','Bar','','Merge','Cat'], }) df = pd.DataFrame(data = d) m = df.A =
行中的第一个和最后一个字符串
。这些字符串
位于特定值右侧时合并。我希望将其更改为低于特定值
import pandas as pd
d = ({
'A' : ['X','Foo','','X','Big'],
'B' : ['No','','','No',''],
'C' : ['Merge','Bar','','Merge','Cat'],
})
df = pd.DataFrame(data = d)
m = df.A == 'X'
def f(x):
s = x[x!= '']
x[s.index[1]] = x[s.index[1]] + ' ' + x[s.index[-1]]
x[s.index[-1]] = ''
return x
df = df.astype(str).mask(m, df[m].apply(f, axis=1))
此代码合并第一个和最后一个字符串
,后跟X
输出:
A B C
0 X No Merge
1 Foo Bar
2
3 X No Merge
4 Big Cat
我希望将其更改为X
值下方的rows
预期产出:
A B C
0 X No Merge
1 Foo Bar
2
3 X No Merge
4 Big Cat
解决方案非常相似,只移动布尔掩码,将第一个NaN替换为False
,并且将[1]
中的索引更改为[0]
,以查看LCT第一个值(列A
):
m = (df.A == 'X').shift().fillna(False)
def f(x):
s = x[x!= '']
x[s.index[0]] = x[s.index[0]] + ' ' + x[s.index[-1]]
x[s.index[-1]] = ''
return x
df = df.astype(str).mask(m, df[m].apply(f, axis=1))
print (df)
A B C
0 X No Merge
1 Foo Bar
2
3 X No Merge
4 Big Cat