尝试使用以下格式将csv文件读入pandas数据帧
dp = pd.read_csv('products.csv', header = 0, dtype = {'name': str,'review': str,
'rating': int,'word_count': dict}, engine = 'c')
print dp.shape
for col in dp.columns:
print 'column', col,':', type(col[0])
print type(dp['rating'][0])
dp.head(3)
Run Code Online (Sandbox Code Playgroud)
这是输出:
(183531, 4)
column name : <type 'str'>
column review : <type 'str'>
column rating : <type 'str'>
column word_count : <type 'str'>
<type 'numpy.int64'>
Run Code Online (Sandbox Code Playgroud)
我可以理解,大熊猫可能会发现很难将字典的字符串表示转换为字典并给出这个和这个.但是如何将"rating"列的内容同时为str和numpy.int64 ???
顺便说一下,不指定引擎或标题的调整不会改变任何东西.
感谢致敬
我有一个字节类型的对象,像这样:
b"{'one': 1, 'two': 2}"
Run Code Online (Sandbox Code Playgroud)
我需要使用python代码从字典中获取字典。我将其转换为字符串,然后如下转换为字典。
string = dictn.decode("utf-8")
print(type(string))
>> <class 'str'>
d = dict(toks.split(":") for toks in string.split(",") if toks)
Run Code Online (Sandbox Code Playgroud)
但是我收到以下错误:
------> d = dict(toks.split(":") for toks in string.split(",") if toks)
TypeError: 'bytes' object is not callable
Run Code Online (Sandbox Code Playgroud) 我有以下字符串,它是一个字典串化的Python字典:
some_string = '{123: False, 456: True, 789: False}'
Run Code Online (Sandbox Code Playgroud)
如何从上面的字符串中获取Python字典?
我尝试使用argparse来学习如何解析给定列表:
parser = argparse.ArgumentParser()
parser.add_argument('--ls', nargs='*', type=str, default = [])
Out[92]: _StoreAction(option_strings=['--ls'], dest='ls', nargs='*', const=None, default=[], type=<type 'str'>, choices=None, help=None, metavar=None)
args = parser.parse_args("--ls 'tomato' 'jug' 'andes'".split())
args
Out[94]: Namespace(ls=["'tomato'", "'jug'", "'andes'"])
args.ls
Out[96]: ["'tomato'", "'jug'", "'ande'"]
args.ls[0]
Out[97]: "'tomato'"
eval(args.ls[0])
Out[98]: 'tomato'
Run Code Online (Sandbox Code Playgroud)
Q1:上面的作品,但是否有更好的方法来访问列表中的值?
然后我尝试用Dictionary解析给定的字典:
dict_parser = argparse.ArgumentParser()
dict_parser.add_argument('--dict', nargs='*',type=dict,default={})
Out[104]: _StoreAction(option_strings=['--dict'], dest='dict', nargs='*', const=None, default={}, type=<type 'dict'>, choices=None, help=None, metavar=None)
arg2 = dict_parser.parse_args("--dict {'name':'man', 'address': 'kac', 'tags':'don'}")
usage: -c [-h] [--dict [DICT [DICT ...]]]
-c: error: unrecognized arguments: - …Run Code Online (Sandbox Code Playgroud) 我有一串
"{a:'b', c:'d',e:''}"
Run Code Online (Sandbox Code Playgroud)
请不要因为字典条目的键未加引号,所以上一个问题中eval("{a:'b', c:'d',e:''}")所建议的简单方法不起作用。
将这个字符串转换成字典的最方便的方法是什么?
{'a':'b', 'c':'d', 'e':''}
Run Code Online (Sandbox Code Playgroud) 我有像这样的字典的字符串:
{"h":"hello"}
Run Code Online (Sandbox Code Playgroud)
我想按照这里的指示将其转换为实际字典
>>> import json
>>>
>>> s = "{'h':'hello'}"
>>> json.load(s)
Run Code Online (Sandbox Code Playgroud)
然而,我收到了一个错误:
回溯(最近通话最后一个):文件"",1号线,在文件"/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/ 初始化的.py",线路286,在加载返回负载(fp.read(),
AttributeError:'str'对象没有属性'read'
我的代码有什么问题,以及如何将字符串转换为实际字典?谢谢.
我有以下文件dic.txt:
{'a':0, 'b':0, 'c':0, 'd':0}
Run Code Online (Sandbox Code Playgroud)
我想阅读其内容并用作字典.输入新数据值后,我需要将它们写入该文件.基本上我需要一个脚本来处理字典,更新它的值并保存它们供以后使用.
我有一个工作脚本,但无法弄清楚如何将dic.txt的内容实际读入脚本中的变量.因为我尝试这个:
file = '/home/me/dic.txt'
dic_list = open(file, 'r')
mydic = dic_list
dic_list.close()
Run Code Online (Sandbox Code Playgroud)
我得到的是mydic是一个str.我无法操纵它的价值观.所以这是问题所在.如何从dic.txt创建字典?
我目前遇到了这个错误,但找不到问题所在。起初,我认为这是因为在 中transformed_data[2],只有 1,但情况似乎并非如此。
ValueError:字典更新序列元素#0的长度为1;2 为必填项
我的代码:
print(transformed_data)
country =transformed_data[0]
continent = transformed_data[1]
transformed_data[2] = transformed_data[2].replace("''",'test')
print(dict(transformed_data[2])) # when I add dict it does the error.
print((transformed_data[2])) # without dict, no error.
Run Code Online (Sandbox Code Playgroud)
没有字典的外壳:
['Qatar', 'ASIA', '{2001: 41.215}', '{2001: 615000}']
{2001: 41.215}
['Cameroon', 'AFRICA', '{2001: 3.324}', '{2001: 16358000}']
{2001: 3.324}
['Democratic Republic of Congo', 'AFRICA', '{2006: 1.553}', '{2006: 56578000}']
{2006: 1.553}
['Bulgaria', 'EUROPE', '{2001: 48.923}', '{2001: 7931000}']
{2001: 48.923}
['Poland', 'EUROPE', '{2001: 306.696}', '{2001: 38489000}']
{2001: 306.696}
['Lesotho', 'AFRICA', "{1975: …Run Code Online (Sandbox Code Playgroud) 我有一个 dict ex 形式的字符串输出。
{'key1':'value1','key2':'value2'}
Run Code Online (Sandbox Code Playgroud)
如何轻松地将其保存为字典而不是字符串?
我有下一个不带引号且带有数组和子字典的字符串:
s ='{source: [s3, kinesis], aws_access_key_id: {myaws1, myaws2}, aws_secret_access_key: REDACTED_POSSIBLE_AWS_SECRET_ACCESS_KEY, bucketName: bucket, region_name: eu-west-1, fileType: zip, typeIngestion: FULL, project: trackingcampaigns, functionalArea: client, filePaths: [s3Sensor/2018/], prefixFiles: [Tracking_Sent, Tracking_Bounces, Tracking_Opens, Tracking_Clicks, Tracking_SendJobs], prefixToTables: {Tracking_Bounces: MNG_TRACKING_EXTRACT_BOUNCES_3, Tracking_Sent: MNG_TRACKING_EXTRACT_SENT_3, Tracking_Clicks: MNG_TRACKING_EXTRACT_CLICKS_3, Tracking_Opens: MNG_TRACKING_EXTRACT_OPENS_3, Tracking_SendJobs: MNG_TRACKING_EXTRACT_SENDJOBS_3}, stagingPath: /zipFiles/}'
Run Code Online (Sandbox Code Playgroud)
我想把它转换成字典。