[英]Is there a way to store a dictionary on each row of a dataframe column using a vectorized operation?
I am attempting to next a dictionary inside of a dataframe.我正在尝试在 dataframe 中查找下一个字典。
here's an example of what I have:这是我所拥有的示例:
x y z
1 2 3
4 5 6
7 8 9
here's an example of what I want:这是我想要的示例:
x y z
1 2 {'z':3}
4 5 {'z':6}
7 8 {'z':9}
For this specific application, the whole point of using pandas is the vectorized operations that are scalable and efficient.对于这个特定的应用程序,使用 pandas 的全部意义在于可扩展且高效的矢量化操作。 Is it possible to transform that column into a column of dictionaries?是否可以将该列转换为字典列? I have attempted to use string concatenation, but then it is stored in pandas as a string and not a dict, and returns later with quotations around the dictionary because it is a string.我曾尝试使用字符串连接,但随后它作为字符串而不是 dict 存储在 pandas 中,并且稍后返回并在字典周围加上引号,因为它是一个字符串。
Example例子
data = {'x': {0: 1, 1: 4, 2: 7}, 'y': {0: 2, 1: 5, 2: 8}, 'z': {0: 3, 1: 6, 2: 9}}
df = pd.DataFrame(data)
Code代码
df['z'] = pd.Series(df[['z']].T.to_dict())
df
x y z
0 1 2 {'z': 3}
1 4 5 {'z': 6}
2 7 8 {'z': 9}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.