Pandas Dataframe 上最干净的 iteration/functional 应用程序,无论长度如何
Cleanest iteration/functional application on Pandas Dataframe regardless of length
我一直在努力将函数干净地迭代或应用到 Pandas 可变长度的数据帧。具体来说,长度为 1 的 DataFrame 切片(Pandas 系列)。
一个简单的例子,一个DataFrame和一个作用于它每一行的函数。数据帧的格式是 known/expected.
def stringify(row):
return "-".join([row["y"], str(row["x"]), str(row["z"])])
df = pd.DataFrame(dict(x=[1,2,3],y=["foo","bar","bro"],z=[-99,1.04,213]))
Out[600]:
x y z
0 1 foo -99.00
1 2 bar 1.04
2 3 bro 213.00
df_slice = df.iloc[0] # This is a Series
通常,您可以通过以下方式之一应用该功能:
stringy = df.apply(stringify,axis=1)
# or
stringy = [stringify(row) for _,row in df.iterrows()]
Out[611]: ['foo-1--99.0', 'bar-2-1.04', 'bro-3-213.0']
## Error with same syntax if Series
stringy = df_slice.apply(stringify, axis=1)
如果数据框为空,或者只有一个条目,这些方法将不再有效。 Series 没有 iterrows()
方法并且 apply
将函数应用于每一列(而不是行)。
是否有更简洁的内置方法 iterate/apply 对可变长度的数据帧起作用?不然就得不停地写繁琐的逻辑。
if type(df) is pd.DataFrame:
if len(df) == 0:
return None
else:
return df.apply(stringify, axis=1)
elif type(df) is pd.Series:
return stringify(df)
我知道有一些方法可以确保您形成长度为 1 的数据帧,但我要问的是在各种 pandas 数据结构上使用一种干净的方法来 apply/iterate ,就像-格式化的数据框或系列。
没有通用的方法来编写一个函数来无缝地处理这两个问题
数据框和系列。您要么需要使用 if-statement
来检查
对于类型,或使用 try..except
来处理异常。
我认为最好在调用 apply
之前确保创建正确类型的对象,而不是做这些事情中的任何一个。例如,不使用df.iloc[0]
which returns一个Series,而是使用df.iloc[:1]
到select一个长度为1的DataFrame。只要当您将切片 range 而不是单个值传递给 df.iloc
时,您将返回一个 DataFrame。
In [155]: df.iloc[0]
Out[155]:
x 1
y foo
z -99
Name: 0, dtype: object
In [156]: df.iloc[:1]
Out[156]:
x y z
0 1 foo -99
我一直在努力将函数干净地迭代或应用到 Pandas 可变长度的数据帧。具体来说,长度为 1 的 DataFrame 切片(Pandas 系列)。
一个简单的例子,一个DataFrame和一个作用于它每一行的函数。数据帧的格式是 known/expected.
def stringify(row):
return "-".join([row["y"], str(row["x"]), str(row["z"])])
df = pd.DataFrame(dict(x=[1,2,3],y=["foo","bar","bro"],z=[-99,1.04,213]))
Out[600]:
x y z
0 1 foo -99.00
1 2 bar 1.04
2 3 bro 213.00
df_slice = df.iloc[0] # This is a Series
通常,您可以通过以下方式之一应用该功能:
stringy = df.apply(stringify,axis=1)
# or
stringy = [stringify(row) for _,row in df.iterrows()]
Out[611]: ['foo-1--99.0', 'bar-2-1.04', 'bro-3-213.0']
## Error with same syntax if Series
stringy = df_slice.apply(stringify, axis=1)
如果数据框为空,或者只有一个条目,这些方法将不再有效。 Series 没有 iterrows()
方法并且 apply
将函数应用于每一列(而不是行)。
是否有更简洁的内置方法 iterate/apply 对可变长度的数据帧起作用?不然就得不停地写繁琐的逻辑。
if type(df) is pd.DataFrame:
if len(df) == 0:
return None
else:
return df.apply(stringify, axis=1)
elif type(df) is pd.Series:
return stringify(df)
我知道有一些方法可以确保您形成长度为 1 的数据帧,但我要问的是在各种 pandas 数据结构上使用一种干净的方法来 apply/iterate ,就像-格式化的数据框或系列。
没有通用的方法来编写一个函数来无缝地处理这两个问题
数据框和系列。您要么需要使用 if-statement
来检查
对于类型,或使用 try..except
来处理异常。
我认为最好在调用 apply
之前确保创建正确类型的对象,而不是做这些事情中的任何一个。例如,不使用df.iloc[0]
which returns一个Series,而是使用df.iloc[:1]
到select一个长度为1的DataFrame。只要当您将切片 range 而不是单个值传递给 df.iloc
时,您将返回一个 DataFrame。
In [155]: df.iloc[0]
Out[155]:
x 1
y foo
z -99
Name: 0, dtype: object
In [156]: df.iloc[:1]
Out[156]:
x y z
0 1 foo -99