python - 将一组值放入数据框中的单元格中
问题描述
更新:我重新措辞并重新思考了这个问题,我认为这个问题最好这样问。
所以我一直在破解这个,没有运气。这是我想要做的一个例子。
我从一个数据框开始:
df = data.frame("one" = c(1,11), "two" = c(2,22), "three" = c(3,33))
one two three
1 2 3
11 22 33
我正在尝试将上述内容变为:
one new
1 c(2,3)
11 c(22,33)
我已经尝试了一些事情,比如嵌套 2 列并尝试映射它们等。也许有一些简单的东西我在这里看不到。我最好希望通过 tidyverse 在 R 中执行此操作,但此时我对任何事情都持开放态度。
必须这样,因为当它转换为 JSON 时,“新”下的值需要采用 [1,2,3] 和 [11,22,33] 的形式。也许在 Python 中更容易?
我正在使用 R 中的jsonlite包与 JSON 进行转换。
谢谢您的帮助。
解决方案
I think this should just be a Map
exercise:
df$new <- Map(c, df$two, df$three)
df
# one two three new
#1 1 2 3 2, 3
#2 11 22 33 22, 33
library(jsonlite)
toJSON(df[c("one","new")])
#[{"one":1,"new":[2,3]},{"one":11,"new":[22,33]}]
If you've got many variables, you can wrap it in do.call
to get it done too:
df$new <- do.call(Map, c(c,df[2:3]))
If tidyverse is your preference, you can purrr it like:
map2(df$two, df$three, c)
推荐阅读
- php - 使用 Ajax 在控件中返回视图
- python - 如何一次在pysftp中写入文件
- c# - AutoCompleteStringCollection - API - 问题的
- css - 增加图标的大小而不增加同一按钮内的文本大小>(文本+图标)>仅增加图标
- r - 如何在 R 中对 .csv 文件进行排序
- javascript - 使用 * 选择器为所有元素切换 CSS 转换按钮
- c++ - 如何在 While 循环中打印出矩阵格式的二维数组
- xamarin - 无法将 Custom.targets 文件添加到启用 Proguard 的 Xamarin Android 项目
- matlab - 如何在给定拟合参数的 MATLAB 中绘制余弦波?
- python-3.x - Asyncio 测试一个使用 loop.call_soon_threadsafe 的函数