Python 为熊猫中的两个数据帧应用函数
我有两个数据帧 df0 df1 我有一个自定义函数:Python 为熊猫中的两个数据帧应用函数,python,pandas,Python,Pandas,我有两个数据帧 df0 df1 我有一个自定义函数: def concat(d0,d1): if d0 is not None and d1 is not None: return '%s,%s' % (d0, d1) return None 我期望的结果是: a b c 0.3,3 0.6,2 d 0.4,0 NaN 如何将该函数应用于这两个数据帧?这里有一个解决方案。 其想法是首先将数据帧简化为一个简单的值列表。这允许您
def concat(d0,d1):
if d0 is not None and d1 is not None:
return '%s,%s' % (d0, d1)
return None
我期望的结果是:
a b
c 0.3,3 0.6,2
d 0.4,0 NaN
如何将该函数应用于这两个数据帧?这里有一个解决方案。
其想法是首先将数据帧简化为一个简单的值列表。这允许您使用并应用函数循环两个数据帧的值。
最后,使用numpy返回原始形状
与和一起使用:
另一种解决方案是最后一次替换NaN
by条件,默认情况下True
s被替换为NaN
:
df = df0.astype(str).add(',').add(df1.astype(str))
m = df0.isnull() | df1.isnull()
print (m)
a b
c False False
d False True
df = df.mask(m)
print (df)
a b
c 0.3,3 0.6,2
d 0.4,0 NaN
如果这是您的特定应用程序,您可以执行以下操作:
#Concatenate the two as String
df = df0.astype(str) + "," +df1.astype(str)
#Remove the nan
df = df.applymap(lambda x: x if 'nan' not in x else np.nan)
在性能方面,您将比使用apply更好
输出
a b
c 0.3,3 0.6,2
d 0.4,0 NaN
df = df0.astype(str).add(',').add(df1.astype(str))
df = df.mask(df.applymap(lambda x: 'nan' in x))
print (df)
a b
c 0.3,3 0.6,2
d 0.4,0 NaN
df = df0.astype(str).add(',').add(df1.astype(str))
m = df0.isnull() | df1.isnull()
print (m)
a b
c False False
d False True
df = df.mask(m)
print (df)
a b
c 0.3,3 0.6,2
d 0.4,0 NaN
#Concatenate the two as String
df = df0.astype(str) + "," +df1.astype(str)
#Remove the nan
df = df.applymap(lambda x: x if 'nan' not in x else np.nan)
a b
c 0.3,3 0.6,2
d 0.4,0 NaN