简体   繁体   English

有没有办法使用向量化操作在 dataframe 列的每一行上存储字典?

[英]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.

相关问题 用于数据帧中多列操作的矢量化解决方案 - Vectorized solution for multiple column operation in a dataframe 矢量与熊猫中DataFrame的每一列的系列相关性 - Correlation of a Series to each column of a DataFrame in Pandas, vectorized 对熊猫数据帧的矢量化操作 - Vectorized operation on pandas dataframe 将组名(来自 groupby)存储到原始 DataFrame 的新列中的矢量化方式? - Vectorized way to store group name (from groupby) into a new column of the original DataFrame? 以字典形式检查数据帧值(作为键,值元组)的矢量化方法? - Vectorized way of checking dataframe values (as key, value tuple) against a dictionary? Pandas:将每行数据存储到以列名为键的字典中 - Pandas : store each row data into a dictionary with column name as key 以矢量化方式将列添加到 Pandas DataFrame 以对其他列值进行调节 - Adding Column to pandas DataFrame in Vectorized way conditioning on other column values 如何在数据框中拆分一列并将每个值存储为新行(以熊猫为单位)? - How to split a column in a dataframe and store each value as a new row (in pandas)? 使用字典逐行向 pandas DataFrame 中的列添加条目 - Adding entries to a column in a pandas DataFrame row-by-row using a dictionary 如何在 Python 中对访问列的每一行的循环进行矢量化 - How can a loop that accesses each row of a column be vectorized in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM