如何在Pandas DataFrame中使用函数 [英] How to use functions with pandas dataframe
本文介绍了如何在Pandas DataFrame中使用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将函数与pandas数据框一起使用.例如:
How can I use function with pandas dataframe. For example:
a | b
london | uk
newyork | usa
berlin | germany
df1 = df[['a', 'b']]
def doSomething(df1):
return df1
doSomething()
将同时返回列a
和b
,但是如何返回只说a
?
doSomething()
will return both columns a
and b
, But how do I return say only a
?
def doSomething(df1):
return df1.a
df1.applymap(doSomething)
AttributeError: ("'str' object has no attribute 'a'", u'occurred at index a')
推荐答案
您可以使用:
df = pd.DataFrame({'a':['london','newyork','berlin'],
'b':['uk','usa','germany'],
'c':[7,8,9]})
print (df)
df1 = df[['a', 'b']]
def doSomething(x):
return x.a
#function works with DataFrame
print (doSomething(df1))
0 london
1 newyork
2 berlin
Name: a, dtype: object
#function works with Series, columns are transformed to index of Series
#return for each row value of Series with index a which is transformed to column in output df
print (df1.apply(doSomething, axis=1))
0 london
1 newyork
2 berlin
dtype: object
如果需要 applymap
它适用于df
的每个元素:
If need applymap
it works with each element of df
:
def doSomething(x):
return x + '___'
#function works with element
print (df1.applymap(doSomething))
a b
0 london___ uk___
1 newyork___ usa___
2 berlin___ germany___
这篇关于如何在Pandas DataFrame中使用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文