如何使用 python pandas 将逗号替换为破折号?

How to replace comma with dash using python pandas?

我有这样一个文件:

name|count_dic
name1 |{'x1':123,'x2,bv.':435,'x3':4}
name2|{'x2,bv.':435,'x5':98}
etc.

我正在尝试将数据加载到数据框中并计算 count_dic 中的键数。问题是 dic 项目用逗号分隔,而且一些键包含逗号。我正在寻找一种方法能够用“-”替换键中的逗号,然后能够像这样在 count_dic.something 中分隔不同的键值对:

name|count_dic
name1 |{'x1':123,'x2-bv.':435,'x3':4}
name2|{'x2-bv.':435,'x5':98}
etc.

这就是我所做的。

df = pd.read_csv('file' ,names = ['name','count_dic'],delimiter='|')
data = json.loads(df.count_dic)

我收到以下错误:

TypeError: the JSON object must be str, not 'Series'

大家有什么建议吗?

一旦 df 定义如上:

# get a value to play around with
td = df.iloc[0].count_dic
td
# that looks like a dict definition... evaluate it?
eval(td)
eval(td).keys() #yup!
#apply to the whole df
df.count_dic = map(eval, df.count_dic)

#and a hint towards your key-counting
map(lambda i: i.keys(), df.count_dic)

您可以使用 ast.literal_eval 作为加载数据框的转换器,因为看起来您的数据更像 Python dict... JSON 使用双引号 - 例如:

import pandas as pd
import ast

df = pd.read_csv('file', delimiter='|', converters={'count_dic': ast.literal_eval})

给你一个 DF:

    name                            count_dic
0  name1  {'x2,bv.': 435, 'x3': 4, 'x1': 123}
1  name2            {'x5': 98, 'x2,bv.': 435}

由于count_dic其实是一个dict,那么可以应用len来获取key的个数,eg:

df.count_dic.apply(len)

结果:

0    3
1    2
Name: count_dic, dtype: int64