Python Forum
Move column to the right if it starts with a letter
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Move column to the right if it starts with a letter
#1
I want to move all columns to the right if my row starts with a letter, not a number.
Dataframe that I have:
var1  var2  var3 ...
9       3       3
4       4       3
ABC   5
Dataframe that I want:
var1  var2  var3 ...
9       3       3
4       4       3
NaN   ABC   5
My code so far:
import pandas as pd
df=pd.read_csv("input.csv", sep=",")

mylist=['A', 'B', 'C', 'D'] # the alphabet list
# identify rows that start with a letter
m = df['NIF (EO)'].str.startswith(mylist)
# define columns to correct 
cols = df.columns[1:]
df.loc[m, cols] = df.loc[m, cols].shift(axis=1)
However, in the last line of the code I am obtaining the error:
"None of [Float64Index([nan, nan, nan, nan, nan, nan, nan, nan, nan, nan,\n ...\n nan, nan, nan, nan, nan, nan, nan, nan, nan, nan],\n dtype='float64', length=200362)] are in the [index]"
What am I doing wrong?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Setup Portable Python on Windows for script starts with double clicks? pstein 0 1,819 Feb-18-2022, 01:29 PM
Last Post: pstein
  Regex: a string does not starts and ends with the same character Melcu54 5 2,427 Jul-04-2021, 07:51 PM
Last Post: Melcu54
  Code starts slowing down? MemoryError AshkanDev 1 2,153 May-19-2020, 11:38 PM
Last Post: AshkanDev
  Run a timer when a functions starts to see how long the function takes to complete Pedroski55 2 2,002 Apr-19-2020, 06:28 AM
Last Post: Pedroski55
  sensor code that starts heater chano 3 3,141 Jun-05-2019, 10:54 AM
Last Post: michalmonday

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020