一种更有效的方式来清洁字符串列并添加新列

用户名

我有一个df具有列的数据框['metric_type', 'metric_value']对于每一行,我想确保我有一列名称等于,'metric_type'并且该列的值等于'metric_value'

我的问题之一是'metric_type'我想摆脱虚假的空间。

考虑数据框df

df = pd.DataFrame([
        ['a ', 1],
        [' b', 2],
        [' c ', 3]
    ], columns=['metric_type', 'metric_value'])

print(df)

  metric_type  metric_value
0          a              1
1           b             2
2          c              3

请注意,每个的值'metric_type'在不同的位置都有空格。

我创建了一个要使用的函数,apply但是要花很长时间。

def assign_metric_vals(row):
    row[row['metric_type'].replace(" ", "")] = row['metric_value']
    return row

使用它时,我得到以下信息:

       a    b    c metric_type  metric_value
0 1.0000  nan  nan          a              1
1    nan 2.00  nan           b             2
2    nan  nan 3.00          c              3

有没有更好的方法(读为“更快”)来完成同一任务?

海盗

将索引设置为metric_type并进行堆叠会更好

df.set_index(df.metric_type.str.replace(' ', ''), append=True).metric_value.unstack()

示范

df = pd.DataFrame([
        ['a ', 1],
        [' b', 2],
        [' c ', 3]
    ], columns=['metric_type', 'metric_value'])

print(df)

  metric_type  metric_value
0          a              1
1           b             2
2          c              3

print(df.apply(assign_metric_vals, 1))

       a    b    c metric_type  metric_value
0 1.0000  nan  nan          a              1
1    nan 2.00  nan           b             2
2    nan  nan 3.00          c              3

或我的方式

idx = df.metric_type.str.replace(' ', '')
d1 = df.set_index(idx, append=True).metric_value.unstack()
print(pd.concat([d1, df], axis=1))

       a    b    c metric_type  metric_value
0 1.0000  nan  nan          a              1
1    nan 2.00  nan           b             2
2    nan  nan 3.00          c              3

定时

使用更大的 df
df1 = pd.concat([df] * 30000, ignore_index=True)

%%timeit
idx = df1.metric_type.str.replace(' ', '')
d1 = df1.set_index(idx, append=True).metric_value.unstack()
pd.concat([d1, df1], axis=1)

10个循环,最佳3:每个循环77.3毫秒

%%timeit
df1.apply(assign_metric_vals, 1)

1次循环,每循环3:57.4 s最佳

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

寻找一种更短,更有效的方式来添加(可能)重复到字符串末尾的内容

寻找一种更有效的方法来根据数据框列中的字典创建新列

需要一种更有效的方式来合并文本文件

寻找一种更有效的方式来初始化字典

将新字符添加到回文。一种有效或动态的方式来检查新字符串是否仍然是回文式?

Neo4j是否有一种更有效的方式来编写多个where-contains?

一种有效的方法来计算多个列中的字符串值以创建新的总计列

需要一种有效的方法来从JSON字符串获取JObject

寻找一种更有效的方法来创建 4 向链表

一种更有效的方法来对netstat命令的结果进行排序

寻找一种更有效的方式编写我的MATLAB代码

一种更简化,更有效的拆分列表方式

寻找一种更有效的方式编写此jquery菜单

如何在python中打印形状?寻找一种不同的、更有效的方式

有没有更有效的方式来扩展字符串?

有没有一种有效的方法来连接golang模板中的字符串

有没有一种有效的方法来连接字符串

有没有一种有效的方法来分割这个字符串

是否有一种更有效的方式以某种方式将项目列表映射到成对列表?

寻找一种有效的方法来返回字符串的一部分

有没有一种更有效的方法来在Access中存储对象容器?

一种更有效的方法来检查是否没有相关项目具有特定值

有没有一种方法可以更有效地格式化此字符串?

更有效的字符串创建方式

是否有一种更有效的方法来将图像居中在浮动div中

一种有效的Scala惯用方式来挑选排序值的前85%?

需要一种有效的方式来存储日期差异

需要一种更有效的方式将JDBC结果集转换为JSON数组

寻找一种更有效的方法来使用 STL 函数检查字符串是否为回文