我正在编写一个Python程序,用于从 .CSV文件列中的每个单元格提取特定的值,然后将所有提取的值设置为新列。
示例列单元格:(这实际上是一小部分,实际单元格包含更多数据)
AudioStreams":[{"JitterInterArrival":10,"JitterInterArrivalMax":24,"PacketLossRate":0.01353227,"PacketLossRateMax":0.09027778,"BurstDensity":null,"BurstDuration":null,"BurstGapDensity":null,"BurstGapDuration":null,"BandwidthEst":25245423,"RoundTrip":520,"RoundTripMax":11099,"PacketUtilization":2843,"RatioConcealedSamplesAvg":0.02746676,"ConcealedRatioMax":0.01598402,"PayloadDescription":"SIREN","AudioSampleRate":16000,"AudioFECUsed":true,"SendListenMOS":null,"OverallAvgNetworkMOS":3.487248,"DegradationAvg":0.2727518,"DegradationMax":0.2727518,"NetworkJitterAvg":253.0633,"NetworkJitterMax":1149.659,"JitterBufferSizeAvg":220,"JitterBufferSizeMax":1211,"PossibleDataMissing":false,"StreamDirection":"FROM-to-
我要提取的一个值是10
和"JitterInterArrival":
之间的数字,"JitterInterArrivalMax"
。但是,由于每个单元格都包含相对较长的字符串和周围的特殊字符(例如“”),因此opener=re.escape(r"***")
和closer=re.escape(r"***")
不起作用。
有人知道更好的解决方案吗?非常感谢!
答案 0 :(得分:1)
IIUC,您有一个json
字符串,并希望从其属性中获取值。所以,给定
s = '''
{"AudioStreams":[{"JitterInterArrival":10,"JitterInterArrivalMax":24,"PacketLossRate":0.01353227,"PacketLossRateMax":0.09027778,"BurstDensity":null,
"BurstDuration":null,"BurstGapDensity":null,"BurstGapDuration":null,"BandwidthEst":25245423,"RoundTrip":520,"RoundTripMax":11099,"PacketUtilization":2843,"RatioConcealedSamplesAvg":0.02746676,"ConcealedRatioMax":0.01598402,"PayloadDescription":"SIREN","AudioSampleRate":16000,"AudioFECUsed":true,"SendListenMOS":null,"OverallAvgNetworkMOS":3.487248,"DegradationAvg":0.2727518,
"DegradationMax":0.2727518,"NetworkJitterAvg":253.0633,
"NetworkJitterMax":1149.659,"JitterBufferSizeAvg":220,"JitterBufferSizeMax":1211,
"PossibleDataMissing":false}]}
'''
您可以
import json
>>> data = json.loads(s)
>>> ji = data['AudioStreams'][0]['JitterInterArrival']
10
在数据框方案中,如果您有一列col
这样的字符串,例如
df = pd.DataFrame({"col": [s]})
您可以使用transform
传递json.loads
作为参数
df.col.transform(json.loads)
以获取Series
的字典。然后,您可以操作这些命令,或仅按上述操作访问数据。