如何将函数仅应用于一行
How to apply a function to only one row
我的日期设置如下:
a b c
1 x1 c1
2 x2 c2
3 x3 c3
并且我只想将函数 f 应用于列 b。
我做了类似的事情:
d2 = d['b'].apply(f)
但我的结果像
a b
1 xt
2 xt
3 xt
我想要 c 列,结果如下:
a b c
1 xt c1
2 xt c2
3 xt c3
如何在不与第一个数据集合并的情况下执行此操作?
我想你尽量不要使用 apply
,因为它比较慢,最好使用 pandas
API 函数:
例如如果需要将列替换为新的常量值:
df['b'] = 'xt'
print (df)
a b c
0 1 xt c1
1 2 xt c2
2 3 xt c3
但是如果apply
是必要的:
def f(x):
return 'xt'
df['b'] = df.b.apply(f)
print (df)
a b c
0 1 xt c1
1 2 xt c2
2 3 xt c3
如果需要新的DataFrame
,先用copy
:
d = df.copy()
def f(x):
return 'xt'
d['b'] = d.b.apply(f)
print (d)
a b c
0 1 xt c1
1 2 xt c2
2 3 xt c3
我的日期设置如下:
a b c
1 x1 c1
2 x2 c2
3 x3 c3
并且我只想将函数 f 应用于列 b。
我做了类似的事情:
d2 = d['b'].apply(f)
但我的结果像
a b
1 xt
2 xt
3 xt
我想要 c 列,结果如下:
a b c
1 xt c1
2 xt c2
3 xt c3
如何在不与第一个数据集合并的情况下执行此操作?
我想你尽量不要使用 apply
,因为它比较慢,最好使用 pandas
API 函数:
例如如果需要将列替换为新的常量值:
df['b'] = 'xt'
print (df)
a b c
0 1 xt c1
1 2 xt c2
2 3 xt c3
但是如果apply
是必要的:
def f(x):
return 'xt'
df['b'] = df.b.apply(f)
print (df)
a b c
0 1 xt c1
1 2 xt c2
2 3 xt c3
如果需要新的DataFrame
,先用copy
:
d = df.copy()
def f(x):
return 'xt'
d['b'] = d.b.apply(f)
print (d)
a b c
0 1 xt c1
1 2 xt c2
2 3 xt c3