我有一个数据框列表,我想为每个数据框计算某些列的字符串值的长度,并使用这些计算出的值创建一个新列:
columns = ['name', 'address', 'email']
newcolumns = ['name_length', 'address_length', 'email_length']
码:
def length(start, i, j):
while i < len(columns):
newcol = newcolumns[i]
col = columns[j]
df_list[start][newcol] = df_list[start][col].str.len()
i += 1
j += 1
start += 1
return df_list
每个单独的数据框都可以像列表一样进行访问,即df[0]
。
我得到的结果仅计算了第一个数据帧的名称和地址长度。其余数据框未计算。
预期结果是所有数据框中的所有指定列均获得了计算结果。理想的答案将是通过使用lambda循环使其自动化来实现。
我该如何修改我的代码?
df_list
,必须对其进行正确索引,以便将新的列分配给中的正确数据框list
,这是通过使用enumerate
。.applymap(len)
对于10万行的数据帧,这是最快的选项。import pandas as pd
# create sample data
data = {'test': range(3), 'name': ['a', 'bc', 'def'], 'address': ['add1', 'add11', 'add111'],
'email': ['[email protected]', '[email protected]', '[email protected]']}
df1 = pd.DataFrame(data)
df2 = pd.DataFrame(data)
df_list = [df1, df2]
columns = ['name', 'address', 'email']
newcolumns = ['name_length', 'address_length', 'email_length']
# iterate through list of dataframes and add _length columns
for i, df in enumerate(df_list):
# create the new columns and assign them to the correct dataframe in the list
df_list[i][newcolumns] = df[columns].applymap(len)
# display(df1)
test name address email name_length address_length email_length
0 0 a add1 [email protected] 1 4 62
1 1 bc add11 [email protected] 2 5 16
2 2 def add111 [email protected] 3 6 18
enumerate
索引列表中的每个数据框就可以完成此操作。
lists
数据框,因为它df
是一个引用,因此在循环中对其进行更新时,会更新其中的适当数据框list
。enumerate
。for df in df_list:
df[newcolumns] = df[columns].applymap(len)
# zip the columns and new column name together
cols = list(zip(columns, newcolumns))
# iterate through list of dataframe
for i, df in enumerate(df_list):
# iterate through the column name pairs
for c in cols:
# create the columns using .str.len()
df_list[i][c[1]] = df[c[0]].str.len()
for i, df in enumerate(df_list):
df_list[i][newcolumns] = df[columns].apply(lambda x: x.str.len())
%%timeit
测试# sample dataframe with 99999 rows
d = pd.concat([df1]* 33333).reset_index(drop=True)
# functions to test
columns = ['name', 'address', 'email']
newcolumns = ['name_length', 'address_length', 'email_length']
cols = list(zip(columns, newcolumns))
def test1(df):
df[newcolumns] = df[columns].applymap(len)
return df
def test2(df):
for c in cols:
df[c[1]] = df[c[0]].str.len()
return df
def test3(df):
df[newcolumns] = df[columns].apply(lambda x: x.str.len())
return df
# tests
%%timeit
test1(d)
[out]:
67.6 ms ± 1.56 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
%%timeit
test2(d)
[out]:
87.6 ms ± 2.26 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
%%timeit
test3(d)
[out]:
89.4 ms ± 543 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句