pandas 中值 (1) 的长度与索引 (156) 的长度不匹配
Length of values (1) does not match length of index (156) in pandas
我正在尝试将 pandas 中的列转换为字典键值对。
输入:
ID col1
1 DAY=20220524
2 DAY=20220525
3 NOON=20220525
预期输出:
ID col1
1 {"DAY":20220524}
2 {"DAY":20220525}
3 {"NOON":20220524}
我写了下面的代码来获取字典键值对。
df_csv[['txt1','txt2']] = df_csv.col1.str.split("=",expand=True)
df_csv['txt2']= df_csv['txt2'].astype(int)
df_csv['col1'] =pd.Series(df_csv.txt2.values,index=df_csv.txt1).to_dict()
有了这些,我得到了字典键值对,但只有一次,因为我有 156 行,所以它给我以下错误。
Length of values (1) does not match length of index (156)
如何遍历所有列来获取这个字典键值对而不是一次?
让我们做
df.col1 = [dict([tuple(x.split('='))]) for x in df.col1]
df
Out[91]:
ID col1
0 1 {'DAY': '20220524'}
1 2 {'DAY': '20220525'}
2 3 {'NOON': '20220525'}
这适用于您的示例:
df_csv.col1 = df_csv.col1.apply(lambda x: {x.split('=')[0]:int(x.split('=')[1])})
输入:
ID col1
0 1 DAY=20220524
1 2 DAY=20220525
2 3 NOON=20220525
输出:
ID col1
0 1 {'DAY': 20220524}
1 2 {'DAY': 20220525}
2 3 {'NOON': 20220525}
我正在尝试将 pandas 中的列转换为字典键值对。
输入:
ID col1
1 DAY=20220524
2 DAY=20220525
3 NOON=20220525
预期输出:
ID col1
1 {"DAY":20220524}
2 {"DAY":20220525}
3 {"NOON":20220524}
我写了下面的代码来获取字典键值对。
df_csv[['txt1','txt2']] = df_csv.col1.str.split("=",expand=True)
df_csv['txt2']= df_csv['txt2'].astype(int)
df_csv['col1'] =pd.Series(df_csv.txt2.values,index=df_csv.txt1).to_dict()
有了这些,我得到了字典键值对,但只有一次,因为我有 156 行,所以它给我以下错误。
Length of values (1) does not match length of index (156)
如何遍历所有列来获取这个字典键值对而不是一次?
让我们做
df.col1 = [dict([tuple(x.split('='))]) for x in df.col1]
df
Out[91]:
ID col1
0 1 {'DAY': '20220524'}
1 2 {'DAY': '20220525'}
2 3 {'NOON': '20220525'}
这适用于您的示例:
df_csv.col1 = df_csv.col1.apply(lambda x: {x.split('=')[0]:int(x.split('=')[1])})
输入:
ID col1
0 1 DAY=20220524
1 2 DAY=20220525
2 3 NOON=20220525
输出:
ID col1
0 1 {'DAY': 20220524}
1 2 {'DAY': 20220525}
2 3 {'NOON': 20220525}