gpt4 book ai didi

python - 使用函数修改 Pandas 数据框

转载 作者:太空宇宙 更新时间:2023-11-03 13:35:15 25 4
gpt4 key购买 nike

这是问题 here 的跟进:如何使用函数修改数据框?假设我想对 a

中的值调用 .upper()
df = pd.DataFrame({'a':['london','newyork','berlin'],
'b':['uk','usa','germany'],
'c':[7,8,9]})

df1 = df[['a', 'b']]

def doSomething(x):
return x.a

print (df1.apply(doSomething, axis=1))
0 london
1 newyork
2 berlin
dtype: object

call `.upper()` on values in `a`:
return
0 LONDON
1 NEWYORK
2 BERLIN
dtype: object

最佳答案

您可以为 a 列调用函数:

def doSomething(x):
return x.upper()

print (df1.a.apply(doSomething))
0 LONDON
1 NEWYORK
2 BERLIN
Name: a, dtype: object

print (df1.a.apply(lambda x: x.upper()))
0 LONDON
1 NEWYORK
2 BERLIN
Name: a, dtype: object

它也适用于:

def doSomething(x):
return x.a.upper()

print (df1.apply(doSomething, axis=1))
0 LONDON
1 NEWYORK
2 BERLIN
dtype: object

但更好的是使用 str.upper它与 NaN 值完美配合:

print (df1.a.str.upper())
0 LONDON
1 NEWYORK
2 BERLIN
Name: a, dtype: object

如果需要添加新列:

df['c'] = df1.a.str.upper()
print (df)
a b c
0 london uk LONDON
1 newyork usa NEWYORK
2 berlin germany BERLIN

关于python - 使用函数修改 Pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41016835/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com