具有此数据框
d = {'objects':[{'Sand':10},{'Seawater': 2, 'Crab': 30},{'Parasol': 50}]}
df = pd.DataFrame(data=d)
我想要这个键值对
{'Small': 1000}
插入具有至少小于40的键值对的每一行。
objects
0 {'Sand': 10, 'Small': 1000}
1 {'Seawater': 2, 'Crab': 30, 'Small': 1000}
2 {'Parasol': 50}
我已经尝试过遍历它,但是会产生'None'。
def your_small(x):
if any(value < 40 for value in x.values()):
return x.update({'Small': 1000})
d = {'objects':[{'Sand':10},{'Seawater': 2, 'Crab': 30},{'Parasol': 50}]}
df = pd.DataFrame(data=d)
df['objects'] = df['objects'].map(your_small)
objects
0 None
1 None
2 None
答案 0 :(得分:3)
正如@ALoll所说,您可能要重新考虑您的方法。
如果要使现有代码正常工作,则必须考虑map的工作原理:必须在map函数中返回一个值。 x.update
返回None
,如果不满足条件,则必须按原样返回x:
def your_small(x):
if any(value < 40 for value in x.values()):
return {**x, 'Small': 1000}
return x
答案 1 :(得分:2)
如果没有必要使用字典,则可以使用MultiIndex。在这里,我假设单独的字典主要具有不重叠的键,因此较长的DataFrame似乎更合适。 (如果大多数字典的键重叠,那么宽的DataFrame可能会更好)
import pandas as pd
df = pd.concat([pd.DataFrame.from_dict(di, orient='index', columns=['N']) for di in d['objects']],
keys=range(len(d['objects'])))
# N
#0 Sand 10
#1 Seawater 2
# Crab 30
#2 Parasol 50
# Determine which original "rows" have at least one value < 40
s = df.N.lt(40).groupby(level=0).any()
df_add = pd.DataFrame({'N': 1000},
index = pd.MultiIndex.from_product([s[s].index, ['Small']]))
# Join them:
df = pd.concat([df, df_add]).sort_index()
# N
#0 Sand 10
# Small 1000
#1 Crab 30
# Seawater 2
# Small 1000
#2 Parasol 50
这是一个具有广泛DataFrame的版本。易于操作,但会变得很大。
df = pd.DataFrame.from_records(d['objects'])
# Sand Seawater Crab Parasol
#0 10.0 NaN NaN NaN
#1 NaN 2.0 30.0 NaN
#2 NaN NaN NaN 50.0
df.loc[df.lt(40).any(1), 'Small'] = 1000
# Sand Seawater Crab Parasol Small
#0 10.0 NaN NaN NaN 1000.0
#1 NaN 2.0 30.0 NaN 1000.0
#2 NaN NaN NaN 50.0 NaN