使用 Pandas 将列转换为行 [英] Convert columns into rows with Pandas
问题描述
所以我的数据集有 n 个日期的位置信息.问题是每个日期实际上是不同的列标题.例如CSV看起来像
位置名称 Jan-2010 Feb-2010 March-2010一个测试"12 20 30B富"18 20 25
我想要的是它的样子
位置名称日期值一个测试"2010 年 1 月 12一个测试"2010 年 2 月 20一个测试"2010 年 3 月 30B富"2010 年 1 月 18B富"2010 年 2 月 20B富"2010 年 3 月 25
我的问题是我不知道列中有多少个日期(尽管我知道它们总是以姓名开头)
更新
从 v0.20 开始,melt
是一阶函数,现在可以使用
df.melt(id_vars=["location", "name"],var_name="日期",value_name="值")地点名称日期值0 测试" 2010 年 1 月 121 B "foo" 2010 年 1 月 182 测试" 2010 年 2 月 203 B "foo" 2010 年 2 月 204 测试" 2010 年 3 月 305 B "foo" 2010 年 3 月 25
<小时>
旧(ER)版本:<0.20
您可以使用 pd.melt
到达那里,然后排序:
(可能想加入一个 .reset_index(drop=True)
,只是为了保持输出干净.)
注意:pd.DataFrame.sort
已弃用,取而代之的是 pd.DataFrame.sort_values
.
So my dataset has some information by location for n dates. The problem is each date is actually a different column header. For example the CSV looks like
location name Jan-2010 Feb-2010 March-2010
A "test" 12 20 30
B "foo" 18 20 25
What I would like is for it to look like
location name Date Value
A "test" Jan-2010 12
A "test" Feb-2010 20
A "test" March-2010 30
B "foo" Jan-2010 18
B "foo" Feb-2010 20
B "foo" March-2010 25
My problem is I don't know how many dates are in the column (though I know they will always start after name)
UPDATE
From v0.20, melt
is a first order function, you can now use
df.melt(id_vars=["location", "name"],
var_name="Date",
value_name="Value")
location name Date Value
0 A "test" Jan-2010 12
1 B "foo" Jan-2010 18
2 A "test" Feb-2010 20
3 B "foo" Feb-2010 20
4 A "test" March-2010 30
5 B "foo" March-2010 25
OLD(ER) VERSIONS: <0.20
You can use pd.melt
to get most of the way there, and then sort:
>>> df
location name Jan-2010 Feb-2010 March-2010
0 A test 12 20 30
1 B foo 18 20 25
>>> df2 = pd.melt(df, id_vars=["location", "name"],
var_name="Date", value_name="Value")
>>> df2
location name Date Value
0 A test Jan-2010 12
1 B foo Jan-2010 18
2 A test Feb-2010 20
3 B foo Feb-2010 20
4 A test March-2010 30
5 B foo March-2010 25
>>> df2 = df2.sort(["location", "name"])
>>> df2
location name Date Value
0 A test Jan-2010 12
2 A test Feb-2010 20
4 A test March-2010 30
1 B foo Jan-2010 18
3 B foo Feb-2010 20
5 B foo March-2010 25
(Might want to throw in a .reset_index(drop=True)
, just to keep the output clean.)
Note: pd.DataFrame.sort
has been deprecated in favour of pd.DataFrame.sort_values
.
这篇关于使用 Pandas 将列转换为行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!